Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access instance variable inside a function in javascript?

Tags:

javascript

oop

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?

like image 792
einstein Avatar asked Dec 28 '22 18:12

einstein


1 Answers

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.

like image 188
Kevin Bowersox Avatar answered Dec 30 '22 09:12

Kevin Bowersox