不能改变属性

Can't change property

本文关键字:属性 能改变 不能      更新时间:2023-09-26

我是javascript新手,在更新属性时遇到了一些问题。我已经尝试了很多不同的方法来解决这个问题。谁能告诉我为什么我不能改变Acceleration类的_x属性?

var acceleration;
function Acceleration()
{
    this._x = 0;
    this.getX = function(){return this._x;};//This one always returns 0;
    this.onSuccess = function(e)
    {
        this._x = e.x;
        document.write( this._x + '<br/>');//This one changes.
        document.write( acceleration._x + '<br/>');//This one remains 0;
    }
    this.update = function()
    {
        intel.xdk.accelerometer.getCurrentAcceleration(this.onSuccess, {adjustForRotation:false});
    }
}
function start()
{
    acceleration = new Acceleration();
    //Start the game.
    loop();
}
function loop()
{
    acceleration.update();
    setTimeout(loop, 1000);
}
document.addEventListener('intel.xdk.device.ready', start, false);

如果我不在_x前面使用this,它会给出相同的结果。

谢谢!

试试这样:

var that = this;
this.getX = function(){return that._x;};
函数中的

this没有引用类对象。

查看this关键字的文档。

谢谢@Pointy。我这样重写了这个函数。

this.update = function()
{
    var object = this;
    intel.xdk.accelerometer.getCurrentAcceleration(
        function(e)
        {
            if(object._x == e.x && object._y == e.y && object._z == e.z){
                _changed = false;
            }else{
                object._x = e.x;
                object._y = e.y;
                object._z = e.z;
                _changed = true;
            }
        }, {adjustForRotation:false});
}