Function.prototype.defer = function(ms) {
let f = this
return function(...args) {
setTimeout(()=>this.apply(this, args), ms); //**
}
};
function f(a, b) {
alert( a + b );
}
f.defer(1000)(1, 2); // shows 3 after 1 second
所以上面的代码给出了一个错误,说“this.apply不是一个函数”。但是,如果我将 (**) 行更改为
setTimeout(()=>f.apply(this, args), ms);
即使 f 仍然引用“this”,代码也运行良好。是什么赋予了?
最佳答案
让我们看一下问题中提供的代码,以了解其工作原理以及 另一个没有。
让我们首先看一下功能示例:
Function.prototype.defer = function (ms) {
let f = this;
return function(...args) {
setTimeout(() => f.apply(this, args), ms);
};
};
function f(a, b) {
alert(a + b);
}
f.defer(1000)(1, 2); // shows 3 after 1 second
// translates to
setTimeout(() => f.appy(this, [1, 2]), 1000);
// ^
// here `this` refers to the global object (window)
让我们看一下不起作用的示例:
Function.prototype.defer = function (ms) {
return function(...args) {
setTimeout(() => this.apply(this, args), ms);
};
};
function f(a, b) {
alert(a + b);
}
f.defer(1000)(1, 2); // shows 3 after 1 second
// translates to
setTimeout(() => this.appy(this, [1, 2]), 1000);
// ^ ^
// here `this` refers to the global object (window)
由于上述上下文中的 this
指向全局对象(窗口),您可以
也可以写成:
setTimeout(() => window.appy(window, [1, 2]), 1000);
由于 window
是一个对象而不是函数,这解释了您所遇到的错误
得到。
关于javascript - 在 Javascript apply 中使用 'this' 作为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55195400/