2011-08-15 5 views
0
function Card(styleAttr, cardInfo) 
{ 
    //Attributes 
    this.styleAttr = styleAttr; 
    this.cardInfo = cardInfo; 

    //Functions 


    constructCard(this.styleAttr); 
} 

function constructCard(styleAttr) { 

    var cardCSS = { 
        'width':styleAttr.width, 
        'height':styleAttr.height, 
        'background-color':'black' 
        } 


    $('<div class="Card"></div>').appendTo('body').css(cardCSS); 
} 

안녕하세요,이 카드 클래스는 매개 변수로 두 가지 다른 객체를 가져옵니다. 그 중 하나는 'width'라는 속성이 포함 된 styleAttr입니다. 이 객체를 constructCard에 전달하지 않으면 styleAttr.width 속성에 액세스 할 수 없습니다. 위의 예제가 작동합니다. 그러나 나는 할 경우이 :메서드 내에서 자바 스크립트 객체 속성에 액세스

function constructCard() { 

    var cardCSS = { 
        'width': this.styleAttr.width, //Undefined 
        'height':styleAttr.height, 
        'background-color':'black' 
        } 


    $('<div class="Card"></div>').appendTo('body').css(cardCSS); 
} 

나는 확실하지 않다 나는 그것이 속성의 액세스 할 수 있도록 클래스에 기능 constructCard을 결합해야합니까 아니면이 통과하도록 강요 오전 그래서 다른 언어로 대부분 코드 객체가 값을 가져옵니다. 아니면 글로벌 변수로 만들겠습니까?

그것은 Moz Doc에서 잡아 내지 못한 간단한 것이어야합니다.

감사

답변

0

아무것도 :

var card_0 = new Card(..., ...) 
card_0.constructCard(); 
+0

감사합니다, 여러분 모두에게, 이것은 C 구문에 가깝기 때문에 선호합니다. –

1

시도 :

function Card(styleAttr, cardInfo) 
{ 
    this.styleAttr = styleAttr; 
    this.cardInfo = cardInfo; 
    this.construct = function() { 
     var cardCSS = { 'width':this.styleAttr.width, 'height':this.styleAttr.height, 'background-color':'black' } 

     $('<div class="Card"></div>').appendTo('body').css(cardCSS); 
    } 
} 

그리고 다음과 같이 사용 :

function Card(styleAttr, cardInfo) { 
    //Attributes 
    this.styleAttr = styleAttr; 
    this.cardInfo = cardInfo; 
} 

Card.prototype.constructCard = function() { 

    var cardCSS = { 
        'width': this.styleAttr.width, 
        'height': this.styleAttr.height, 
        'background-color':'black' 
        }; 


    $('<div class="Card"></div>').appendTo('body').css(cardCSS); 
} 

다음 : 옛날부터 프로토 타입 상속 문제

var card = new Card(styleAttr, cardInfo); 
card.construct(); 
+0

두 단계로 된 개체 구성으로 보입니다. 객체가 생성되었지만 아직 기술적으로 준비가되지 않았기 때문에 한 번만 새로운 호출로 모든 것을 설정하는 것을 목표로했습니다. 개체를 사용하기 위해 누군가가해야 할 추가 단계가 문서화되어 있어도 소리가 나지 않습니다. 실제로 생성자 내부에서이 처리를해야한다고 말할 수도 있지만, 생성자를 부풀게하기 때문에 함수로 분리하려고합니다. 나는 실험을해야 할 것이다. –

관련 문제