簡體   English   中英

對象內的JavaScript新對象重復

[英]JavaScript new objects inside objects duplicating

我正在冒險深入JavaScript,遇到了一個我無法理解的小問題。

我所了解的有關編程的一切都是自學的,這個問題背后可能有我從未聽說過的術語,所以我不知道該怎么稱呼。

我將解釋我遇到的問題。

我一直在為HTML5畫布編寫一個框架,用於顯示2d和3d圖形。

如您所料,我已經設計了一個元素類,這些元素在畫布上具有根據我放在一起的向量類構建的位置。

我遇到的問題是,如果我創建兩個“文本”對象,然后在其position對象中調用一個函數,則“ Text”對象的所有位置都將更改為此值:

    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();

非常感激任何的幫助!

這是我完整的Element課

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

從外觀上,您將位置聲明為對象上的“靜態”變量,這意味着它將改變。 要僅對特定對象進行更改,您需要以下條件之一:

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的原型。

我找到了答案! 謝謝您的幫助! 解決方案是使父對象進行調用

由於某種原因,我不完全了解。

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM