javascript 为什么我在这个例子中得到“无法读取未定义的属性‘文本’”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31776883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why am I getting "Cannot read property 'text' of undefined" in this example?
提问by user5124106
I'm in the progress of making a game, which you can by clicking here. My first question is why I'm getting
我正在制作一款游戏,您可以点击这里。我的第一个问题是为什么我得到
Cannot read property 'text' of undefined
无法读取未定义的属性“文本”
when the snake (green blocks) hits the food (red circle).
当蛇(绿色方块)碰到食物(红色圆圈)时。
The line that is invoking the error is the this.scoreElem.text(newScore);
from
调用错误的行是this.scoreElem.text(newScore);
from
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!");
}
});
}
}
The instance of a StatHandler
object is created by
StatHandler
对象的实例是由
var H = new StatHandler("#total-score", "#fruit-eaten");
inside a $(document).ready
, where I've verified that #total-score
and #fruit-eaten
are valid selectors since they are id
s of elements I've verified to be in the DOM.
在 a 中$(document).ready
,我已经验证了它#total-score
并且#fruit-eaten
是有效的选择器,因为它们是id
我已经验证为在 DOM 中的元素的 s。
Full code can be seen here.
完整代码可以在这里看到。
Also, as you may have noticed, I'm trying to update the score on the server side and send the updated score back to the client. But, this doesn't prevent the client from cheating by running
此外,您可能已经注意到,我正在尝试更新服务器端的分数并将更新后的分数发送回客户端。但是,这并不能阻止客户端通过运行来作弊
SG.stats.incrementScore(1000000000);
in the JS console. How do I prevent cheating?
在 JS 控制台中。如何防止作弊?
回答by Mouser
At this moment your this
keyword isn't referring to the object you want it to. It's bound to the scope of the success function. So this.scoreElem
is undefined. Calling text
on undefined will raise an error.
此时您的this
关键字不是指您想要的对象。它绑定到成功函数的范围。所以this.scoreElem
是未定义的。调用text
undefined 会引发错误。
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!");
}
});
}
}
Referring this
via self
will get it to work. Since JavaScript uses lexical scoping, the variable self
will be available when the ajax success function is parsed.
引用this
viaself
将使其工作。由于 JavaScript 使用词法范围,self
当解析 ajax 成功函数时,该变量将可用。
回答by charlietfl
You can use context
property of $.ajax
options to set what this
is within the callbacks if you don't want it to be the settings object.
如果您不希望它成为设置对象,则可以使用选项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!");
}
});
}