[英]Why am I getting TypeError: Cannot read property 'now' of undefined
[英]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.