在回调中调用方法
call methods in callback
我有这个试试class:
function Try () {
console.log('Start')
this.Something( function() {
console.log('asd')
this.Some()
})
}
Try.prototype.Something = function (callback) {
console.log('hi all')
callback()
}
Try.prototype.Some = function () {
console.log('dsa')
}
但是当我尝试在回调部分调用 Some 方法时,它给了我一个错误,显示 this.Some is not a function
。问题是什么?我该如何解决这个问题?
scope of this
在不同的function
里面是不同的,即使是在function
里面
您需要在 self
中保留 this
外部函数并使其成为
function Try () {
console.log('Start')
var self = this;
self.Something( function() {
console.log('asd')
self.Some();
})
}
我有这个试试class:
function Try () {
console.log('Start')
this.Something( function() {
console.log('asd')
this.Some()
})
}
Try.prototype.Something = function (callback) {
console.log('hi all')
callback()
}
Try.prototype.Some = function () {
console.log('dsa')
}
但是当我尝试在回调部分调用 Some 方法时,它给了我一个错误,显示 this.Some is not a function
。问题是什么?我该如何解决这个问题?
scope of this
在不同的function
里面是不同的,即使是在function
您需要在 self
中保留 this
外部函数并使其成为
function Try () {
console.log('Start')
var self = this;
self.Something( function() {
console.log('asd')
self.Some();
})
}