开发者

Accessing Javascript object attribute within method

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

Hi, this Card class get's two other object's as it's parameters. One of them is styleAttr which contains a property named 'width'. Unless I pass this object to the constructCard, I cannot access the styleAttr.width property. The above example works. But if I开发者_运维问答 do this:

function constructCard() {

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


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

Mostly code in other languages so I'm not sure, do I have to bind the function constructCard to the class to be able to access it's properties or am I forced to pass the object's to get the values. Or am I supposed to make them global variables?

It must be something simple I didn't catch from the Moz Doc's.

Thanks


Try:

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

And then you use it like this:

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


Nothing wrong with plain old prototype inheritance:

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

Then:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜