【问题标题】:Why object property became undefined when using setInterval为什么使用 setInterval 时对象属性变得未定义
【发布时间】:2016-04-11 19:07:19
【问题描述】:

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

属性来自它的论点。

我尝试在onload后每2秒调用一次该方法,结果显示未定义。

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

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

我将能够显示文本“嗨”。这是为什么呢?

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);
}

感谢您的帮助...

【问题讨论】:

标签: javascript object methods this setinterval


【解决方案1】:

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

我认为您想要做的是使用闭包使 showWord() 的上下文成为这样的给定词实例:

        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() 返回初始输入的值。 (关闭很难解释,如果您需要更多信息,恐怕最好由其他人解释它们。)

【讨论】:

  • 嘿,这对我来说是一个很好而清晰的解释,谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-04-14
  • 2021-11-10
  • 2012-01-10
  • 2015-11-08
  • 1970-01-01
  • 2020-01-05
  • 1970-01-01
  • 2019-10-02
相关资源
最近更新 更多