在以下代码中,centerX的值不是数字(NAN)。我假设在计算属性centerX的值时,属性“x”和“width”是有效的。看来情况并非如此。属性初始化的顺序是什么?依赖初始化和依赖依赖的顺序
var some_object = { x: 50,
width: 100,
centerX: this.x + this.width/2 // This prints centerX as NAN
};
在以下代码中,centerX的值不是数字(NAN)。我假设在计算属性centerX的值时,属性“x”和“width”是有效的。看来情况并非如此。属性初始化的顺序是什么?依赖初始化和依赖依赖的顺序
var some_object = { x: 50,
width: 100,
centerX: this.x + this.width/2 // This prints centerX as NAN
};
this
是function execution context依赖于功能如何得到所谓的属性。在你的情况,因为没有功能,this
将默认为window
,而这些属性不存在,该读作:
undefined + undefined/2 == NaN
您可以创建一个getter:
var obj = {
x: 50,
width: 100,
center: function(){
return this.x + this.width/2;
}
};
obj.center(); // `this` is the receiver
或者,你可以在声明后将属性分配给对象:
var obj = {
x: 50,
width: 100
};
obj.center = obj.x + obj.width/2;
这取决于您希望如何使用对象。第一个是便携式的,您可以方便地计算属性。
在您的代码中,当计算出centerX的值时,this
并不像您期望的那样代表对象some_object
。
如果您在浏览器控制台中键入您的代码,则this
是浏览器窗口。
根据您的声明在代码中的位置,this
可能是任何东西。这事没有(两个或无)命名x
可以是属性,包括命名width
属性:
this.x === undefined
或
this.width === undefined
所以
this.x + this.width/2 === NaN
相反,你可以创建你的对象
var some_object = {
x: 50,
width: 100
}
,并将其添加一个功能
some_object.foo = function() {
// Here, 'this' exists and represents 'some_object'
this.centerX = this.x + this.width/2;
}
// call the function
some_object.foo();
然后你会预期
some_object.centerX === 50