Javascript “的价值是什么?”;这";在下面的setTimeout中的匿名函数中?
我已经重写了下划线.js延迟函数,如下所示。在使用apply()进行修补之后,它就可以工作了,但我不完全理解setTimeout内的匿名函数中apply中的“this”指的是什么Javascript “的价值是什么?”;这";在下面的setTimeout中的匿名函数中?,javascript,underscore.js,this,Javascript,Underscore.js,This,我已经重写了下划线.js延迟函数,如下所示。在使用apply()进行修补之后,它就可以工作了,但我不完全理解setTimeout内的匿名函数中apply中的“this”指的是什么 _.delay = function(func, wait) { var args = Array.prototype.slice.call(arguments, 2); setTimeout(function() { return func.apply(this, args);
_.delay = function(func, wait) {
var args = Array.prototype.slice.call(arguments, 2);
setTimeout(function() {
return func.apply(this, args);
}, wait);
};
此
指的是setTimeout()
和setInterval()函数中的窗口
。
如果要避免这种副作用,可以“绑定”this
的值:
_.delay = function(func, wait, thisArg) {
var args = Array.prototype.slice.call(arguments, 2);
thisArg = thisArg || this;//assume a default value
setTimeout(function() {
return boundFunction.apply(thisArg, args);
}, wait);
};
然后您可以将此
的值传递给.delay()
,或者默认为
另一种方法是在将函数传递给\uuu.delay()
之前绑定函数:
它是全局对象(浏览器中的aka
window
)。全局,取决于JS引擎<代码>窗口,节点
,等等。解决方案:@user2864740漂亮的指针。啊,这就是我要找的:
function a() {console.log(this);}
_.delay(a.bind({foo:'bar'}), 1000); //prints {foo: 'bar'}