我是javascript的新手,在更新属性方面遇到了一些问题。我已经尝试了很多不同的方法来解决这个问题。有人可以告诉我为什么我无法更改_x
类的Acceleration
属性。
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);
如果我在this
前面不使用_x
,则会得到相同的结果。
谢谢!
答案 0 :(得分:0)
尝试这样的事情:
var that = this;
this.getX = function(){return that._x;};
函数中的 this
不是指您的类对象。
关于关键字this
,请参阅此documentation。
答案 1 :(得分:0)
谢谢@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});
}
看起来很有效。