我对这个例子有点困惑:
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);
我知道首先这个(let f)包含函数f,但是这个在返回函数中呢?据我所知,它是未定义的,不是吗(f.apply(undefined, args)
) ?如果是这样,我们为什么要使用apply ?为什么它会起作用?
我所理解的是
undefined
在你的例子中使用了of It。
我们为什么要使用
call
和为什么它工作吗?
不知道你为什么提到call
。也许你想要apply
。原因是您不知道f
是什么,也不知道它是否需要一些this
绑定,这取决于它是如何调用的。考虑到这一点并在延迟执行中不丢失this
绑定是很好的。
下面是defer
的用户想要使用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