我想知道如何通过访问同一对象中的变量值来声明新变量。我试过this.x
了object.x
。都说cannot read property of undefined
。
例如
var board = {
width: 188,
height: 110,
left: (320 - board.width)/2,
top: (480 - this.height)/8,
};
我想知道如何通过访问同一对象中的变量值来声明新变量。我试过this.x
了object.x
。都说cannot read property of undefined
。
例如
var board = {
width: 188,
height: 110,
left: (320 - board.width)/2,
top: (480 - this.height)/8,
};
您不能这样做,因为board
在构造对象并执行分配之前未定义。(此外,this
没有在函数之外定义。)您必须使用多个语句。
var board = { width : 188, height : 110 };
board.left = (320 - board.width) / 2;
board.top = (480 - board.height) / 8;
替代方案:您可以考虑使用立即调用的函数表达式:
var board = (function(){
var width = 188
,height = 110;
return {
width: width
,height: height
,left: (320 - width)/2
,top: (480 - height)/8
};
})();