4

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);
user2864740
  • 60,010
  • 15
  • 145
  • 220
rel1x
  • 2,351
  • 4
  • 34
  • 62
  • For future reference, this title is pretty general. If you can be a bit more specific about your code and tag it correctly, it'll help people other people with the same question find an answer better. – Jack Guy Aug 12 '15 at 04:08
  • 1
    @J4G - I've gone ahead and renamed the title. – Andrew Shepherd Aug 12 '15 at 04:18

1 Answers1

7

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531