简体   繁体   English

为什么在此示例中出现“无法读取未定义的属性'文本'”?

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

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); 引发错误的行是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. $(document).ready ,在这里我已验证#total-score#fruit-eaten是有效的选择器,因为它们是我已验证为在DOM中的元素的id

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. 在JS控制台中。 How do I prevent cheating? 如何防止作弊?

At this moment your this keyword isn't referring to the object you want it to. 目前,您的this关键字未指向您想要的对象。 It's bound to the scope of the success function. 它绑定到成功函数的范围。 So this.scoreElem is undefined. 因此this.scoreElem是未定义的。 Calling text on undefined will raise an error. 在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!");
            }
        });
    }
}   

Referring this via self will get it to work. 参照this通过self会得到它的工作。 Since JavaScript uses lexical scoping, the variable self will be available when the ajax success function is parsed. 由于JavaScript使用词法作用域,因此在解析ajax成功函数时,变量self将可用。

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!");
            }
        });
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我为什么会收到TypeError:无法读取未定义的属性“现在” - Why am I getting TypeError: Cannot read property 'now' of undefined 为什么我在此 for 循环中无法读取未定义的属性“startsWith”? - Why am I getting Cannot read property 'startsWith' of undefined in this for loop? 为什么会出现“无法读取未定义的html属性”? - Why am I getting “Cannot read property of html undefined”? 为什么我越来越无法读取未定义错误的属性? - why I am getting, cannot read property of undefined error? 为什么我收到“ TypeError:无法读取未定义的属性” length” - Why am I getting 'TypeError: Cannot read property 'length' of undefined' 为什么我得到这个“无法读取未定义的属性”长度”? (JavaScript) - Why am I getting this 'cannot read property 'length' of undefined'? (JavaScript) 当我可以打印未定义的变量时,为什么会出现“无法读取未定义错误的属性”? - Why Am I Getting “Cannot read property of undefined error” When I Can Print the Undefined Variable? 为什么会收到此错误类型错误:无法读取未定义的属性“客户端” - Why am getting this error TypeError: Cannot read property 'client' of undefined 为什么我会收到Uncaught TypeError:无法在分配时读取未定义的属性“ 0”? - why am I getting Uncaught TypeError: Cannot read property '0' of undefined on assign? 尝试访问嵌入的Google地图时,为什么会出现无法读取未定义的属性“ getCenter”的问题? - Why am I getting Cannot read property 'getCenter' of undefined when trying to access my embed google map?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM