2011-08-15 60 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

所以看来这将是一个两步对象构造。由于对象是创建的,但目前还没有技术上的准备,所以我打算只用一次新的调用就完成一次设置。我的意思是,即使有文件证明,使用该物体必须做的额外步骤听起来也不正确。其实你可能会说我应该在构造函数里面做这个处理,但是我有点想把它分解成一个函数,因为它有点膨胀了构造函数。我必须尝试。 –