javascript setTimeout 调用错误
我想调用 window.setTimeot
函数我的自定义范围,因此我使用 call
方法,但是有问题。
function foo() {
this.bar = function() {
console.log("keep going");
window.setTimeout.call(this,this.bar,100);
}
this.bar();
}
new foo;
在 Firefox 下,这只会打印到控制台 1 行,然后什么也不打印,而在 google chrome 下,它会抛出 类型错误
。
我的代码有什么问题?
I want to invoke the window.setTimeot
function with my custom scope so I use the call
method, but there is something wrong.
function foo() {
this.bar = function() {
console.log("keep going");
window.setTimeout.call(this,this.bar,100);
}
this.bar();
}
new foo;
under Firefox this prints to the console only 1 line and then nothing, and under google chrome it throws a TypeError
.
What is the problem in my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
call
在这里没有帮助:它使用this
对象调用setTimeout
,但回调函数本身仍然是从全局范围调用的。您真正想做的是这样的:编辑: 如果您确实想要类似于
call
方法,您可以使用bind
绑定this
值function:但是,这是新的 ECMAScript 5 规范的一部分,尚未得到所有浏览器的支持。
Using
call
does not help here: it callssetTimeout
with yourthis
object, but the callback function itself is still called from the global scope. What you really want to do is something like this:Edit: If you really want something similar to the
call
approach, you can usebind
which binds thethis
value for a function:However, this is part of the new ECMAScript 5 spec which is not yet supported by all browsers.