Skip to content Skip to sidebar Skip to footer

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 = me

Solution 1:

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()

functionGreeting(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);
};

newGreeting("Hello, world!", 1);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --><scriptsrc="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

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

Post a Comment for "Settimeout Fails To Bind To "this" Prototype Function"