2013-08-22 1 views
0

EASELJS 라이브러리에서 개체를 상속하고 있습니다. 문제를 단순화하기 위해 코드를 최소 형식으로 축소했습니다.자바 스크립트 개체 멤버 변수가 복제되지 않습니다.

this.TESTProg = this.TESTProg || {}; 

(function() { 
    var _jsbutton = function(x, y, text, icon) { 
     p.init(x, y, text, icon); 
    }; 

    var p = _jsbutton.prototype = new createjs.Container(); 

    p.x = 0; 
    p.y = 0; 
    p.text = null; 
    p.icon = null; 

    p.init = function(x, y, text, icon) { 
     this.x = 0 + x; 
     this.y = 0 + y; 
     this.text = "" + text; 
     this.icon = null; 
    }; 

    TESTProg._jsbutton = _jsbutton; 
})(); 

그럼 내가 다른 JS 객체에서 사용 :

var buttoncancel = new SJSGame._jsbutton(
      profileselConfig.cancelx, //this is defined in another jsfile: 
      profileselConfig.cancely, 
      "cancel", "_cancel.png"); 

    console.log(buttoncancel.y); //this gives 240 

    var buttoncancel2 = new SJSGame._jsbutton(
      profileselConfig.cancelx, 
      profileselConfig.cancely - 40, 
      "cancel", "_cancel.png"); 

    console.log(buttoncancel.y); //this gives 200 
    console.log(buttoncancel2.y); //this gives 200 

    buttoncancel2.y = 100; 
    console.log(buttoncancel.y); //this now gives 200 (not changed by the second object) 
    console.log(buttoncancel2.y); //this now gives 100 

설정 파일이 :

var _profileselConfig = function(){ 
    this.cancelx = 0; 
    this.cancely = 240; 
}; 

profileselConfig = new _profileselConfig(); 

그리고 내가 무슨 잘못을하고있는 중이 야

는 전 클래스가?

참조를 전달하지 않으려면 이미 0을 사용하고있어 작동하지 않습니다. 지금 어떻게해야합니까? 어떤 제안? 감사.

+0

[EaselJS : 누군가가 데모에 사용 된 상속 패턴을 설명 할 수 있습니까?] (http://stackoverflow.com/questions/18008421/easeljs-can-somebody-explain-the-inheritance-pattern-used-in -demos) – Bergi

답변

0

생성자에 p.init이 아닌 this.init을 호출해야합니다.

p.init으로 전화하면 initthis은 프로토 타입을 나타냅니다. 따라서 인스턴스를 만들 때마다 p.init 호출이 의 프로토 타입을 모두 수정합니다._jsbutton 개체가 수정됩니다.

두 단추의 x/y 값이 같기 때문에 둘 다 동일한 프로토 타입에서 위치를 얻고 마지막 실행자가 프로토 타입 값을 설정합니다. buttoncancel2.y을 생성자 외부에 설정하면 해당 인스턴스에 고유 한 y 속성이 부여되므로 더 이상 공유 프로토 타입 값을 사용하지 않습니다.

생성자에서 this.init을 호출하는 경우 this (init)은 새로 생성 된 인스턴스를 나타냅니다. 인스턴스는 x, y, texticon에 대한 공유 프로토 타입 값을 더 이상 사용하지 않습니다.

사이드 노트 : " 참조를 전달하지 않으려면 0 +를 사용하고 있습니다."- 기본 유형은 항상 복사되기 때문에 이것은 필요하지 않습니다.

+0

고마워요. 그래서 내 p가 다른 객체를 구분하지 않는 새로운 인스턴스 일 때도. 알았다 –