Access an instance variable inside an anonymous function inside prototype method
This is actually a follow up question to my previous question, Access instance variable inside a function in javascript?.
I want t开发者_如何学编程o access an instance variable inside an anonymous function inside prototype method.
function MyObject(){
//Instance variables
this.handler;
}
//Methods
MyObject.prototype.enableHandler = function(){
var button = document.getElementById('button');
button.onclick = function(){
this.handler();//Is not working
}
}
var myObject = new MyObject();
myObject.handler = function(){
alert('Hello World!');
}
myObject.enableHandler();
JSFiddle http://jsfiddle.net/3cmvZ/
The example above was just to clarify how I can access an instance variable inside an anonymous function inside a prototype method. I already know that button.onclick = this.handler
works.
The problem is not that the anonymous function is in the prototype, but rather that it is an event handler (which is not invoked as a method).
The problem is that in your onclick handler, the this
keywords is bound to the windows
object, not to the myObject
instance that the prototype is set on. You can store the object in a that
variable and create a closure:
function MyObject(){
//Instance variables
this.handler;
}
//Methods
MyObject.prototype.enableHandler = function(){
var button = document.getElementById('button');
var that = this;
button.onclick = function(){
that.handler();//Should be working
}
}
var myObject = new MyObject();
myObject.handler = function(){
alert('Hello World!');
}
myObject.enableHandler();
this.handler
is not in the same scope. You need to declare it as:
MyObject.prototype.enableHandler = function() {
var button = document.getElementById("button");
button.onclick = this.handler;
}
As you are simply calling the event directly, you need not wrap it in another function.
Update based on your comment:
MyObject.prototype.enableHandler = function() {
var button = document.getElementById("button");
var $this = this;
button.onclick = function() {
$this.handler();
}
}
You need to make a local variable that is in the same scope as the anonymous function.
精彩评论