2012-01-08 6 views
1

JavaScript의 깊이에 모험을하고 있으며 머리를 감을 수없는 작은 문제가 있습니다.오브젝트 내부의 JavaScript 새 오브젝트

프로그래밍에 대해 알고있는 모든 것은 스스로 가르쳐지며,이 문제는 내가 들어 본 적이없는 용어를 가지고있을 수 있으므로 무엇이 호출 될지 모른다.

내가 겪고있는 문제에 대해 설명하겠습니다.

저는 2 차원 및 3 차원 그래픽을 표시하기위한 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.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.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.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

+0

설명에 전체 클래스를 추가했습니다. – user4030

+0

다음 텍스트 클래스를 추가하겠습니다. – user4030

관련 문제