Saturday, 26 March 2016

javascript - setTimeout fails to bind to "this" prototype function





I wrote a code and I want to see "Hello, world!" each second, but I've got undefined and I can't find where is my mistake.



function Greeting(message, delay) {
this.message = message;
setTimeout(this.blowUp, delay * 1000);
}

Greeting.prototype.blowUp = function () {
console.log(this.message);
};


new Greeting("Hello, world!", 1);

Answer



Because when setTimeout callback is executed, it is executed with window as its context(object referred by this (this) in the function) by default.



You can pass a custom context to the callback by using Function.bind()






function Greeting(message, delay) {
this.message = message;
setInterval(this.blowUp.bind(this), delay * 1000); //use setInterval since you want to repeat the callback execution
}

Greeting.prototype.blowUp = function() {
snippet.log(this.message);
};

new Greeting("Hello, world!", 1);








Note: You will have to use setInterval instead of setTimeout() if you want to repeat the callback execution


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...