javascript setTimeout调用错误 [英] javascript setTimeout call error

查看:169
本文介绍了javascript setTimeout调用错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用 window.setTimeot 功能与我的自定义范围,所以我使用 调用 方法,但有问题。

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;

这只打印到控制台只有1行,然后没有,在谷歌浏览器下它会抛出一个 TypeError

under Firefox this prints to the console only 1 line and then nothing, and under google chrome it throws a TypeError.

我的代码有什么问题?

推荐答案

使用调用在这里没有帮助:它用这个调用 setTimeout 对象,但仍然从全局范围调用回调函数本身。你真正想做的是这样的事情:

Using call does not help here: it calls setTimeout with your this object, but the callback function itself is still called from the global scope. What you really want to do is something like this:

function foo() {
    var self = this;
    this.bar = function() {
        console.log("keep going");
        window.setTimeout(function() { self.bar(); }, 100);
    }
    this.bar();
}

编辑:如果你真的想要类似于调用方法,您可以使用 bind ,它绑定函数的 this 值:

If you really want something similar to the call approach, you can use bind which binds the this value for a function:

window.setTimeout(this.bar.bind(this), 100);

但是,这是所有浏览器尚不支持的新ECMAScript 5规范的一部分。

However, this is part of the new ECMAScript 5 spec which is not yet supported by all browsers.

这篇关于javascript setTimeout调用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆