2011-08-15 59 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); 
} 

嗨,這個卡類獲取其他兩個對象的參數。其中之一是styleAttr,它包含一個名爲'width'的屬性。除非將此對象傳遞給構造卡,否則我無法訪問styleAttr.width屬性。上面的例子起作用。但是,如果我這樣做:訪問方法內的Javascript對象屬性

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

沒有錯,普通的舊原型繼承:

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_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); 
    } 
} 

然後你使用這樣的:

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

所以看來這將是一個兩步對象構造。由於對象是創建的,但目前還沒有技術上的準備,所以我打算只用一次新的調用就完成一次設置。我的意思是,即使有文件證明,使用該物體必須做的額外步驟聽起來也不正確。其實你可能會說我應該在構造函數裏面做這個處理,但是我有點想把它分解成一個函數,因爲它有點膨脹了構造函數。我必須嘗試。 –