Function.prototype.defer = function(ms) {
let f = this;
console.log(this);
return function(...args) {
console.log(this);
setTimeout(() => f.apply(this, args), ms);
}
};
let user = {
name: "John",
sayHi() {
alert(this.name);
}
}
user.sayHi = user.sayHi.defer(1000);
user.sayHi();
Hi! Here is the gist of this code: we must add to the prototype of all functions the method defer(ms), that returns a wrapper, delaying the call by ms milliseconds. It must work like this:
`function f(a, b) {
alert( a + b );
}
f.defer(1000)(1, 2); // shows 3 after 1 second`
As it should be also work fine for object's methods, in this code this explicitly assigned to let f. My question is about this. Why in first console.log this it's method sayHi, and in second - it's object user? Thanks for your answers.