如何将上下文传递到setTimeout
?我想在1000毫秒后调用this.tip.destroy()
,如果是this.options.destroyOnHide
。我该怎么做呢?
if (this.options.destroyOnHide) {
setTimeout(function() { this.tip.destroy() }, 1000);
}
当我尝试上面的操作时,this
引用的是窗口。
发布于 2012-02-16 01:36:00
在Internet Explorer以外的浏览器中,您可以在延迟后将参数一起传递给函数:
var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
所以,你可以这样做:
var timeoutID = window.setTimeout(function (self) {
console.log(self);
}, 500, this);
就性能而言,这比作用域查找(将this
缓存到超时/间隔表达式之外的变量中),然后创建闭包(通过使用$.proxy
或Function.prototype.bind
)要好。
使其在来自Webreflection的IE中工作的代码
/*@cc_on
(function (modifierFn) {
// you have to invoke it as `window`'s property so, `window.setTimeout`
window.setTimeout = modifierFn(window.setTimeout);
window.setInterval = modifierFn(window.setInterval);
})(function (originalTimerFn) {
return function (callback, timeout){
var args = [].slice.call(arguments, 2);
return originalTimerFn(function () {
callback.apply(this, args)
}, timeout);
}
});
@*/
发布于 2014-05-26 20:19:39
注意:这在IE中不起作用
var ob = {
p: "ob.p"
}
var p = "window.p";
setTimeout(function(){
console.log(this.p); // will print "window.p"
},1000);
setTimeout(function(){
console.log(this.p); // will print "ob.p"
}.bind(ob),1000);
发布于 2012-10-21 01:18:16
如果你使用的是underscore
,你可以使用bind
。
例如。
if (this.options.destroyOnHide) {
setTimeout(_.bind(this.tip.destroy, this), 1000);
}
https://stackoverflow.com/questions/2130241
复制相似问题