簡體   English   中英

為什么在此示例中出現“無法讀取未定義的屬性'文本'”?

[英]Why am I getting “Cannot read property 'text' of undefined” in this example?

我正在開發游戲,您可以點擊此處 我的第一個問題是為什么我越來越

無法讀取未定義的屬性“文本”

當蛇(綠色方塊)擊中食物(紅色圓圈)時。

引發錯誤的行是this.scoreElem.text(newScore);

function StatHandler ( totalScoreSelector, fruitEatenSelector )
{
    this.scoreElem = $(totalScoreSelector);
    this.fruitEeatenElem = $(fruitEatenSelector);

    this.incrementScore = function ( incAmount )
    {
        $.ajax({
            type: "POST",
            url: "Play/IncrementScore?amount=" + incAmount,
            success: function (newScore)
            {
                this.scoreElem.text(newScore);
            },
            error: function ( ) 
            {
                alert("error occured!");
            }
        });
    }
}

StatHandler對象的實例由創建

var H = new StatHandler("#total-score", "#fruit-eaten"); 

$(document).ready ,在這里我已驗證#total-score#fruit-eaten是有效的選擇器,因為它們是我已驗證為在DOM中的元素的id

完整的代碼可以在這里看到。

另外,您可能已經注意到,我正在嘗試在服務器端更新分數並將更新后的分數發送回客戶端。 但是,這不會阻止客戶端通過運行來作弊

SG.stats.incrementScore(1000000000);

在JS控制台中。 如何防止作弊?

目前,您的this關鍵字未指向您想要的對象。 它綁定到成功函數的范圍。 因此this.scoreElem是未定義的。 在undefined上調用text將引發錯誤。

function StatHandler ( totalScoreSelector, fruitEatenSelector )
{
    this.scoreElem = $(totalScoreSelector);
    this.fruitEeatenElem = $(fruitEatenSelector);

    this.incrementScore = function ( incAmount )
    {
        var self = this;
        $.ajax({
            type: "POST",
            url: "Play/IncrementScore?amount=" + incAmount,
            success: function (newScore)
            {
                self.scoreElem.text(newScore);
            },
            error: function ( ) 
            {
                alert("error occured!");
            }
        });
    }
}   

參照this通過self會得到它的工作。 由於JavaScript使用詞法作用域,因此在解析ajax成功函數時,變量self將可用。

您可以使用context的屬性$.ajax選擇要設置的this是在回調中,如果你不希望它是設置對象。

this.incrementScore = function ( incAmount )
    {

        $.ajax({
            type: "POST",
            context: this, // set callback context
            url: "Play/IncrementScore?amount=" + incAmount,
            success: function (newScore)
            {
                this.scoreElem.text(newScore);
            },
            error: function ( ) 
            {
                alert("error occured!");
            }
        });
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM