我在这个方法中有一个类方法和一个闭包。我如何从闭包中访问类成员?
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
});
}
}
最佳答案
使用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 个月后重新访问它,我可能会以不同的方式编写上面的代码。我喜欢这里的私有(private)/公开曝光。此外,不需要任何奇特的绑定(bind)或类似的东西 ^.^
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"
关于javascript - 在闭包中访问类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18561620/