为什么对象 属性 在使用 setInterval 时变得未定义

Why object property became undefined when using setInterval

如下代码,我创建了一个名为"test"的对象,并赋予它属性和方法。

属性来自它的论点。

并且我尝试在onload后每2秒调用一次该方法,结果显示undefined。

但是如果我只调用不使用 setInterval() 的方法,就像这样

window.onload = function() {
   giveword.showWord();
}

我将能够显示文本 "Hi".. 这是为什么?

var giveword = new test("Hi");

function test(word) {
    this.word = word;
}

test.prototype.showWord = function() {
    document.getElementById("msg_box").innerHTML = this.word;
}

window.onload = function() {
    setInterval(giveword.showWord, 2000);
}

感谢帮助...

原因是因为在您的 test.prototype.showWord 函数中,您的 this 对象指的是调用该函数的上下文,即从 setInterval 调用时的 window 对象。

我想你想做的是使用闭包使 showWord() 的上下文成为 giveword 实例,如下所示:

        var giveword = new test("Hi");

        function test(word) {
            this.word = word;
        }

        test.prototype.showWord = function() {
            document.getElementById("msg_box").innerHTML = this.word;
        }


        window.onload = function(){
            setInterval(function(){giveword.showWord();}, 2000); // <<-- here's the closure
        }

不同之处在于,使用闭包时,您是在告诉 setInterval 函数在声明 setInterval 时调用上下文中的函数。当声明 setInterval 时,范围内有一个名为 giveword 的变量,它有一个 showWord() 方法,returns 初始输入的值。 (闭包很难解释,如果您需要更多信息,恐怕最好由其他人来解释。)