Javascript 使用setInterval时对象属性未定义的原因

Javascript 使用setInterval时对象属性未定义的原因,javascript,object,methods,this,setinterval,Javascript,Object,Methods,This,Setinterval,正如下面的代码,我创建了一个名为“test”的对象,并给出了它的属性和方法 这个属性来自于它的论点 我尝试在onload之后每2秒调用一次该方法,结果显示undefined 但是如果我只调用方法而不使用setInterval(),就像这样 window.onload = function() { giveword.showWord(); } 我将能够显示文本“嗨”。。为什么呢 var giveword = new test("Hi"); function test(word) {

正如下面的代码,我创建了一个名为“test”的对象,并给出了它的属性和方法

这个属性来自于它的论点

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

但是如果我只调用方法而不使用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);
}

感谢您的帮助…

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

我认为您要做的是使用闭包使showWord()的上下文成为给定的Word实例,如下所示:

        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
        }
var giveword=新测试(“Hi”);
功能测试(word){
这个单词=单词;
}
test.prototype.showWord=函数(){
document.getElementById(“msg_box”).innerHTML=this.word;
}
window.onload=函数(){

setInterval(function(){giveword.showWord();},2000);//问题是当你像那样将它传递给
setInterval
时,
this
没有设置为
giveword
。可能会重复读取
this
谢谢你的信息!嘿,这对我来说是一个很好的清晰的解释,谢谢!