JavaScript'这'window.setInterval中的作用域

JavaScript 'this' scope in window.setInterval

本文关键字:作用域 JavaScript window setInterval      更新时间:2023-09-26

我是Javascript的新手,所以有人能告诉我为什么"this"的值会根据我从哪个函数调用它而变化吗。我不是把addquote称为一种方法吗(从这里开始的#3?我写这篇文章主要是作为OOP练习,所以如果有人能给我介绍好的文档,我将不胜感激。谢谢!

function QuoteBox(text, author){
    this.quote = new Quote(text, author);
    this.element = document.getElementById("quotebox");
}

QuoteBox.prototype.removequote = function(c){
        // do some animation here and maybe move the removal to a callback
    this.element.children[0].innerHTML = "";
    this.element.children[1].innerHTML = "";
    c();
}
QuoteBox.prototype.addquote = function(){
    console.log(this); // outputs the window ?!
    this.element.children[0].innerHTML =quote.text;
    this.element.children[1].innerHTML =quote.author;
}
QuoteBox.prototype.refresh = function(){
    console.log(this); // outputs the quotebox object
    this.quote.generate();
    this.removequote(this.addquote);
}
$(document).ready(function() {
    quotebox = new QuoteBox("Quote", "Author");
    window.setInterval(function(){
        quotebox.refresh();
    }, 5000);
});

当您调用这样的函数时:

this.removequote(this.addquote); 

您将addquote的引用传递到removequote中,因此您的c包含对addquote方法的引用,而不是上下文。当您调用c()时,此方法将在全局上下文中调用。可以使用bind将上下文绑定到方法。像这样:

this.removequote(this.addquote.bind(this));

因为您在removequote函数中调用c()而没有为此调用指定目标对象。所以,应该是c.call(this)

关于这个话题的好文章-http://unschooled.org/2012/03/understanding-javascript-this/