Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout fails to bind to "this" prototype function [duplicate]

Tags:

javascript

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);
like image 779
rel1x Avatar asked Mar 16 '23 02:03

rel1x


1 Answers

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);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="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

like image 172
Arun P Johny Avatar answered Apr 26 '23 00:04

Arun P Johny