我正在使用 OOP 原则构建一个 jQuery 应用程序,并且我正在尝试实现一个外部添加的回调函数,该函数从我的对象内部调用一个方法。
function testObject() {
var self = this;
var functions = new Array();
this.updateObject = function() {
console.log('updated')
}
this.addFunction = function(func) {
functions.push(func)
}
this.callFunctions = function() {
$.each(functions, function(key, value) {
functions[key]()
})
}
}
var myobject = new testObject();
myobject.addFunction(
function() {
$(':text').on('change', function() {
return self.updateObject();
})
}
)
这是我正在构建的插件的一个过于简化的版本。回调工作正常,但我无法使用 self.updateObject();在它的内部,因为它输出非法调用。
如何从回调内部正确调用方法?
最佳答案
问题是 self
超出了回调函数的范围,因为该函数仅在其定义范围内具有变量。回调是在 testObject
外部定义的。
解决方案是使用 Function.prototype.call(self)
将回调函数中的 this
上下文绑定(bind)到 self
,当您在 callFunctions()
中调用它时。然后在回调中,您可以使用 this
来引用 testObject
实例。在您的回调示例中,它包含一个 jQuery 事件,因此您将丢失 this
上下文。要纠正这个问题,您可以在 jQuery 更改事件之前创建一个等于 this
的本地 self
。
function testObject() {
var self = this;
var functions = new Array();
this.updateObject = function() {
console.log('updated')
}
this.addFunction = function(func) {
functions.push(func)
}
this.callFunctions = function() {
$.each(functions, function(key, value) {
functions[key].call(self); // call it and bind the context to self
})
}
}
var myobject = new testObject();
myobject.addFunction(
function() {
var self = this; // needed because the change event will overwrite 'this'
$(':text').on('change', function() {
return self.updateObject(); // use self to access testObject
})
}
)
myobject.callFunctions();
或者,您可以将 self
作为参数传递给回调。为此,请将 .call()
行更改为:
functions[key].call(null, self);
并更改回调以接受如下参数:
myobject.addFunction(
function(self) { // self as an argument
$(':text').on('change', function() {
return self.updateObject(); // use self to refer to testObject
})
}
)
关于javascript - 面向对象的 JavaScript : Call method from inside of Callback Function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23721871/