2012-01-08 50 views
1

我正在冒險進入JavaScript的深處,遇到了一個小問題,我無法擺脫困境。JavaScript中的新對象內部對象複製

我所瞭解的關於編程的一切都是自學的,這個問題可能有一些我從來沒有聽說過的術語,所以我不知道它會被稱爲什麼。

我會解釋我遇到的問題。

我一直在編寫一個用於顯示2d和3d圖形的HTML5畫布框架。如你所料,我設計了一個元素類,這些元素在畫布上的位置是由我放在一起的矢量類構建而成的。

我遇到的,如果我做兩個「文本」對象,然後調用它們的位置物體內部的功能問題,「文本」的對象的所有位置更改到這個值:

var usernameLabel = new C.Text('Username:'); 
    usernameLabel.position.set(30,30) 

    var username = new C.Text('Hello World'); 
    username.position.set(0,70) 

    console.log(usernameLabel.position.x) // 0 when it should be 30 

我敢肯定,有一些我錯過了,我只是無法弄清楚什麼。

C.Text.prototype = new C.Element(); 

    C.Element.position = new JC.Vector(); 

任何幫助將不勝感激!

這是我的全要素類

C.elements = 0; 

C.Element = function() 
{ 
    this.id = C.elements ++; 

    this.position = new C.Vector(); 
    this.rotation = new C.Vector(); 
    this.style = new C.Style(); 

    this.children = []; 
} 

C.Element.prototype = { 

    constructor : C.Element, 

    addChildObject : function(o) 
    { 
     return this.children.push(o); 
    }, 

    removeChildObject : function(o) 
    { 
     this.children.splice(o,1); 
    } 

} 

文本類

C.Text = function(string) 
{ 
    this.string = string || ''; 
} 

C.Text.prototype = new C.Element(); 
C.Text.prototype.constructor = C.Text(); 

我也從C.Element內置多個類明顯,例如:

C.Rectangle = function(width, height) 
{ 
    this.style.setSize(width,height); 
} 

C.Rectangle.prototype = new C.Element(); 
C.Rectangle.prototype.constructor = new C.Rectangle(); 



var usernameLabel = new C.Text('Username:'); 
usernameLabel.position.set(30,30) // 0,70? 

var username = new C.Text(''); 
username.position.set(0,70) // 0,70 

var rect = new C.Rectangle(20,0); 
rect.position.set(30,80) // 90,80? 

var rect2 = new C.Rectangle(20,0); 
rect2.position.set(90,80) // 90,80 

回答

0

我找到了答案!謝謝您的幫助!解決辦法是讓父對象進行呼叫

由於我沒有完全理解的原因。

C.Text = function(string) 
{ 
    C.Object.call(this) 

    this.string = string || ''; 
    return this; 
} 

C.Text.prototype = new C.Object(); 
C.Text.prototype.constructor = C.Text; 
1

從它的外觀,你聲明位置爲對象上的「靜態」變量,這意味着它會改變。爲了使只有特定的對象上改變你需要以下之一:

C.Element.prototype.position = new JC.Vector(); 

或對象中的一個函數裏面

this.position = new JC.Vector(); 

這些聲明是針對特定對象,其中項目因爲C.Element.position聲明是爲了在對象的所有實例中都是相同的。

更新

,而不用聲明C.Text.prototype = new C.Element()的。嘗試使用C.Text.prototype = C.Element.prototype。希望這會解決你的問題。而不是創建一個新的對象,它基於它的原型直接C.Element

+0

@ user4030發佈到jsBin或jsFiddle,我可以看看它。這裏很難閱讀。 – Ktash 2012-01-08 17:33:12

+0

我在說明中添加了完整的課程。 – user4030 2012-01-08 17:38:09

+0

然後我會添加我的文本類: – user4030 2012-01-08 17:42:35