繁体   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