let's assume i have this code
function UselessDelay() {
this.petalCount = Math.floor(Math.random() * 12) + 1;
}
UselessDelay.prototype.declare = function () {
console.log('I am a beautiful flower with ' + this.petalCount + ' petals!');
};
var ud = new UselessDelay();
ud.start();
where start method could be written in different ways using call or bind methods:
UselessDelay.prototype.start = function () {
var self = this;
window.setTimeout(function () {
self.declare.call(self);
}, 3000);
};
or
UselessDelay.prototype.start = function () {
window.setTimeout(this.declare.bind(this), 3000);
};
I'm really ok with there examples and do understand them. Let's look at another start method
UselessDelay.prototype.start = function () {
window.setTimeout(this.declare, 3000);
};
The result of this function fires after 3 secs, it's ok. But why the "petalCount" property of this is undefined, but reference to "declare" function works just fine?
Another weird behaviour happens when this.declare execution is passed to setTimeout function as an argument.
UselessDelay.prototype.start = function () {
window.setTimeout(this.declare(), 3000);
};
This function won't wait 3 secons. It executes right away, but "petalCount" is not undefined. I assume passing and invoking function kinda breaks setTimeout function while executing and thus this remains unchanged.