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