我有以下代码:
function Obj() {
var container = [1, 2, 3];
this.callback_m = function() {
if (obj.exists(this)) {
//...
};
}
this.exists = function(element) {
return !(container.indexOf(element) == -1);
}
}
var obj = new Obj();
$(".elem").on('click', obj.callback_m);
我使用对象的方法作为回调函数。很明显,当调用此方法时,“this”被设置为触发事件的元素。我将“this”元素传递给对象的“exists”方法,以查看它是否存在于集合中。但是,要获得“存在”方法,我需要引用引用我的对象的“obj”变量。
obj.exists(this)
但这肯定是一个错误的选择,因为 'obj' 可以有不同的名称或超出范围。而且我也不能在这里使用 bind() ,因为我需要对触发事件的元素的引用。
我想出的唯一解决方案是使用闭包来记住对自身的引用。这是它现在的样子:
function Obj() {
var container = [1, 2, 3];
var self = this;
this.callback_m = function() {
if (self.exists(this)) {
//...
};
}
this.exists = function(element) {
return !(container.indexOf(element) == -1);
}
}
这个问题还有其他解决方案吗?我提出的方法有哪些潜在问题?