解决此范围界定问题的最佳方法是什么?
NAMESPACE.myObject = {
foo: 'foo',
init: function() {
$('.myBtn').on('click', this.myMethod);
},
myMethod: function() {
console.log($(this), foo);
}
};
NAMESPACE.myObject.init();
console.log 的结果应该是被点击的 jQuery 对象和 myObject 的属性 foo。我将如何实现这一点?
最佳答案
基本上你不能有超过一个this
,所以需要解决它。
作为一般规则,创建一个作用域变量(在下面的示例中为 THIS
)来保存您想要从任何其他范围内保留/访问的范围。
不过,您需要在单击处理程序内部保留对 myMethod 的调用中的 this
,因此您不能只传递 myMethod
,因为它丢失了 myObject
实例。
NAMESPACE.myObject = {
this.foo: 'foo',
init: function() {
var THIS = this;
$('.myBtn').on('click', function(){
// "this" here is the button clicked
// "THIS" is still the myObject instance
THIS.myMethod(this);
});
},
myMethod: function(element) {
// "this" here is myObject
// The clicked element was passed as parameter "element" instead
console.log($(element), this.foo);
}
};
NAMESPACE.myObject.init();
我希望我已经足够清楚地解释这个 :)
正如 jfriend00 指出的那样,您还可以使用 bind
来基本上创建一个具有 this
作用域的函数调用(非常可爱),但这并不在 IE8 或更早版本上工作。
关于javascript - 对象文字 jquery 事件范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23566835/