4

How can I in the easiest way access an instance variable inside a function?

function MyObject(){

     //Instance variables
     this.handler;

     //Methods
     this.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();

Note that I can set button.onclick = this.handler;. This is just an example. The main question is how I can access this.handler inside that function?

I can also define a new variable var handler = this.handlerto access this.handler. But If a change handlerwill this.handler also be changes?

1
  • 2
    You mentioned jQuery but I don't see you using it... Commented Jun 30, 2011 at 17:39

1 Answer 1

10
function MyObject(){

     //Instance variables
     this.handler;
     var that = this;  //notice change
     //Methods
     this.enableHandler = function(){
         var button = document.getElementById('button');
         button.onclick = function(){
             that.handler();//Is not working  notice the change
         }
     }

}
var myObject = new MyObject();
myObject.handler = function(){
    alert('Hello World!');
}
myObject.enableHandler();

If you assign this to a var within the scope of the outer function, it is passed to the inner functions scope chain. Within your inner function referencing this refers to the inner function, referencing the variable you assigned this, in our case "that", refers back to that object.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok if I change that.handler will this.handler also be changed?
yes but you also need to do the var that = this; assignment, look at the two places i put notice change in the comments.

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.