2012-07-17 78 views
1

所以我是新的Javascript中的对象定义,并试图编写一个程序,作为一个练习旋转对象。我的问题是,当我试图定义对象时,某些对象属性依赖于对象的其他部分。我不确定这是否被允许,因为在我所有的搜索中我都找不到它的任何例子。使用这种。在JavaScript对象定义

我的问题基本上是这样的:我可以使用以前定义的对象属性来定义该对象。最基本的例子是这样的:

var alfred = { 
    dogs: 1, 
    cats:this.dogs+1, 
} 

这是允许的吗?如果是的话,这是正确的语法?我需要使用“这个”的原因。是因为我推新创建的对象不工作我的objects.The代码的阵列低于:

obj.push({ 
    canvas:document.getElementById(canvasName), 

    canvasName:"canvas"+objNum, 
    image: img, 
    width:objWidth, 
    height:objHeight, 
    centerX:posX, 
    centerY:posY, 
    speed:speeds, 
    hypSquare:Math.sqrt((this.width*this.width)+(this.height*this.height)), 
    angleInSquare:Math.atan(this.height/this.width), 
    angle:startAngle, 
    angleTotal:this.angle+this.angleInSquare, 
    offX:(this.hypSquare* Math.cos(this.anglesTotal))/2, 
    offY:(this.hypSquare* Math.sin(this.anglesTotal))/2, 
    centeredX:this.centerX-this.offX, 
    centeredY:this.centerY-this.offY, 
}) 

,当我叫

console.log(obj[objNum].hypSquare); 

(其中objNum只是指数)我会得到NaN,即使我打电话

console.log(obj[objNum].width); 

我将得到objWidth的值。是否只是一个语法问题,或者是我对物体的理解存在根本上的缺陷......

预先感谢您的时间!

艾萨克

回答

2

不,你不能这样做。你必须关闭object initializer然后添加其他属性,如:

var alfred = { 
    dogs: 1 
}; 
alfred.cats = alfred.dogs + 1; 

因此,对于你obj.push电话,你将不得不使用一个临时变量(像上面这样alfred),你不能只用一个内联对象初始值设定项。

+0

太棒了!非常感谢您的建议。我害怕我必须这样做,但这就是生活...... – Cabbibo 2012-07-17 16:58:27

1

你不能那样做。但是,您可以使用对象构造函数。

function Person(canvasName, objNum) { 
    this.canvas = document.getElementById(canvasName); 

    this.canvasName = "canvas" + objNum; 
    ... 
    this.centeredY = this.centerY - this.offY; 
} 

obj.push(new Person("alfred", 3)); 
相关问题