【发布时间】:2014-07-20 10:01:49
【问题描述】:
假设我有一个结构如下的对象:
var obj = {
prop1: "val",
init: function(){
this.bindings();
},
bindings: function(){
$(".some-class").on('click', this.someFunction);
},
someFunction(){
this.prop1--; // this does not refer to the right scope
console.log(this); //logs $(".some-class")[0] object
}
}
如果在someFunction 中我希望上下文是obj 而不是$(".some-class")[0] 对象怎么办?
目前,我正在使用这个解决方案:
$(".some-class").on('click', $.proxy(this.someFunction, this));
它正在工作,但我在问自己是否有更好/优雅的方法来解决这个问题。
【问题讨论】:
-
this.someFunction.bind(this)MDN bind -
jQuery 覆盖了这个,所以你可以使用 jQuery.proxy() 之类的东西,或者只是做一些聪明的 var self=this 并使用 self 代替 this
-
var self = this之类的东西不会改变function的执行范围 -
@epascarello 谢谢,不知道。
标签: javascript jquery scope