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.handler
to access this.handler
. But If a change handler
will this.handler
also be changes?
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.
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