I have a class method and a closure within this method. How I can access to class member from closure?
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
});
}
}
Use of Function.prototype.bind
will help you here
Person = function(x) {
this.x = x;
}
Person.prototype.myMethod = function() {
$('#myBtn').click(function() {
this.x;
}.bind(this));
};
You can use some better separation of code here too
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);
};
Note if you want to support older browsers, check out es5-shim
EDIT
I'm revisiting this after ~6 months and I would probably write the above code differently. I like the private/public exposure here. Also, no need for any fanciful binds or anything like that ^.^
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With