3

This is actually a follow up question to my previous question, Access instance variable inside a function in javascript?.

I want to 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.

0

2 Answers 2

4

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();
Sign up to request clarification or add additional context in comments.

2 Comments

If I change that.handlerwill this.handler also be changed?
as long as that and this are the same object then yes.
2

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.

2 Comments

Forgot to mention that the example 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
If I change $this.handler will this.handler also be changed?'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.