2012-07-17 38 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)); 
相關問題