我在这个方法中有一个类方法和一个闭包。我如何从关闭访问类成员?
Person = function(x) {
this.x = x;
}
Person.prototype = {
myMethod: function() {
$('#myBtn').click( function() {
// how to access to this.x? the this reference points in another context
});
}
}
答案 0 :(得分:8)
使用Function.prototype.bind
会对您有所帮助
Person = function(x) {
this.x = x;
}
Person.prototype.myMethod = function() {
$('#myBtn').click(function() {
this.x;
}.bind(this));
};
您也可以在这里使用更好的代码分离
Person = function(x) {
this.x = x;
};
Person.prototype.myMethod = function {
$('#myBtn').click(this.clickHandler.bind(this));
};
Person.prototype.clickHandler = function(event) {
console.log(this.x);
};
注意如果您想支持旧浏览器,请查看es5-shim
修改强>
我在约6个月后重新审视这个问题,我可能会以不同的方式编写上述代码。我喜欢这里的私人/公众曝光。此外,不需要任何幻想的束缚或类似 ^。^
function Person(x, $button) {
// private api
function onClick(event) {
console.log(x);
}
function myMethod() {
$button.click();
}
// exports
this.x = x;
this.myMethod = myMethod;
// init
$button.click(onClick);
}
var b = $("#myBtn"),
p = new Person("foo", b);
p.x; // "foo"
p.myMethod(); // "foo"
btn.click(); // "foo"
答案 1 :(得分:2)
只需将this
分配给其他变量,例如_this
:
Person = function(x) {
this.x = x;
}
Person.prototype = {
myMethod: function() {
var _this = this;
$('#myBtn').click( function() {
console.log(_this.x);
});
}
}
答案 2 :(得分:1)
Person = function(x) {
this.x = x;
}
Person.prototype = {
myMethod: function() {
var self = this;
$('#myBtn').click( function() {
// Access to self.x
});
}
}
答案 3 :(得分:0)
代理在这里非常有用。
现在,您正在为click事件分配匿名函数。默认情况下,上下文将是事件,并与您的对象分开。
使用代理,您可以为(回调)函数分配特定的上下文。因此,当事件触发时,您正在处理您的人物对象。
initialize()
这样的单独函数,并将myMethod()
作为处理程序。使用JQuery.proxy()
将对象的上下文分配给事件处理程序。
Person.prototype = {
initialize: function() {
$('#myBtn').click($.proxy(this.myMethod, this));
},
myMethod: function(event) {
...
console.log(this); // Person object
}
}
只是为了引出我和@ naomik解决方案之间的区别:
JQuery.proxy()
是对上下文的临时或狭义分配。Function.prototype.bind()
是一个强大的上下文分配。该方法将“永远”绑定到您提供的上下文。