我正在使用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();在其内部,因为它输出了非法调用。
如何从回调内部正确调用方法?
答案 0 :(得分:1)
问题是self
超出了回调函数的范围,因为该函数只在其定义范围内包含变量。回调是在testObject
。
当您在this
中调用回调函数时,解决方案是使用Function.prototype.call(self)
将回调函数中的self
上下文绑定到callFunctions()
。然后在回调中,您可以使用this
来引用testObject
实例。在您的回调示例中,它包含一个jQuery事件,因此您将丢失this
上下文。要纠正这一点,您可以在jQuery更改事件之前创建等于self
的本地this
。
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
})
}
)
答案 1 :(得分:0)
function testObject() {
var self = this;
var functions = new Array();
this.updateObject = function() {
console.log('updated')
}
this.addFunction = function(func) {
functions.push(func.bind(self)) // Bind the context
}
this.callFunctions = function() {
$.each(functions, function(key, value) {
functions[key]()
})
}
}
var myobject = new testObject();
myobject.addFunction(
function() {
var self = this;
$(':text').on('change', function() {
return self.updateObject();
})
}
)
或者您也可以使用它:
myobject.addFunction(
function() {
$(':text').on('change', this.updateObject);
}
)