I am sorry for that the simple question first. But I just want to know what happen in the code below.
var indexobj = {
test : 1,
testFunction : function() {
document.getElementById('AA').innerHTML = indexobj.test++;
//this is i wanted
document.getElementById('BB').innerHTML = this.test++;
//NaN
setTimeout(indexobj.testFunction,1000);
},
}
setTimeout(indexobj.testFunction,1);
Here is the sample link below
http://jsfiddle.net/apss/JR5Xk/28/
Why in this example the ‘this’ inside the ‘testFunction’ function doesn’t mean ‘indexobj’ this object? Thanks for your help.
Because setTimeout
runs callback function in global object context, meaning that indexobj.testFunction
is invoked with this
being a window
object.
So you can either do
setTimeout(function() {
indexobj.testFunction();
},1000);
or using Function.prototype.bind
to create wrapper function with correct context:
setTimeout(indexobj.testFunction.bind(indexobj), 1000);
Another modern option from ES2015 is to use arrow function that preserves lexical context:
setTimeout(() => indexobj.testFunction(), 1000);
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