JavaScript中的setTimeout和“this”

JavaScript中的setTimeout和“this”

我有一个使用该setTimeout函数的方法,并调用另一个方法。在初始加载方法2工作正常。但是,在超时后,我收到一个错误,表示method2未定义。我在这做错了什么?

例如:

test.prototype.method = function(){
    //method2 returns image based on the id passed
    this.method2('useSomeElement').src = "http://www.some.url";
    timeDelay = window.setTimeout(this.method, 5000);};test.prototype.method2 = function(name) {
    for (var i = 0; i < document.images.length; i++) {
        if (document.images[i].id.indexOf(name) > 1) {
            return document.images[i];
        }
    }};


万千封印
浏览 497回答 3
3回答

智慧大石

在this你使用中setTimeOut通过自身的范围界定。var "foo = this;"在t&nbsp;est.prototype.method函数内部创建并使用foo。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript