I'm a bit confused about this example:
Function.prototype.defer = function(ms) {
let f = this; // I know content of this - it is function f
return function(...args) {
setTimeout(() => f.apply(this, args), ms);
}
};
// check it
function f(a, b) {
alert( a + b );
}
f.defer(1000)(1, 2);
I know that first this (let f) contains function f, but what about this in returned function? It is undefined as I understand, isn't it (f.apply(undefined, args)) ? If so, why should we use apply and why does it work?
It is
undefinedas I understand
It is in your example use of of it.
why should we use
calland why does it work?
Not sure why you mention call. Maybe you intended apply. The reason is that you don't know know what f is and whether it needs some this binding, which depends on how it is called. It is nice to take that into account and not lose the this binding in the deferred execution.
Here is an example where the user of defer wants to use this:
Function.prototype.defer = function(ms) {
let f = this;
return function(...args) {
setTimeout(() => f.apply(this, args), ms);
}
};
// check it
function f(a, b) {
console.log(this + a + b );
}
f.defer(1000).call(3, 1, 2); // 6