简体   繁体   中英

Why am I getting property undefined in my JavaScript object?

I created a function to generate and return an object:

function TickersObj(tag, array, boolLots, boolOptions, boolDisplay) {
    tag         = tag         || {};
    array       = array       || [];
    boolLots    = boolLots    || false;
    boolOptions = boolOptions || false;
    boolDisplay = boolDisplay || true;

    console.log('tag = ', tag);
    console.log('array = ', array);
    console.log('boolLots = ', boolLots);
    console.log('boolOptions = ', boolOptions);
    console.log('boolDisplay = ', boolDisplay);

    this.assoTikArray     = array;
    this.lotsOfTags       = boolLots;
    this.tagOptions       = boolOptions;
    this.tagsHoverDisplay = boolDisplay;
    return this;
}

Later down in my code I pass in the values like so:

switch(type) {
    case 'tagsPanel':
        tag.tickers  = data.data.ticker_tag.tickers;
        var tickersObj = TickersObj(tag, tag.tickers, tag.lotsOfTags, true, true);
        return tickersObj;
        break;
        ....

However once it gets to this line this.assoTikArray = array; I get the error Cannot set property assoTikArray of undefined

在此处输入图片说明

Thoughts on what I'm doing wrong?

You are simply calling the function without context (ie TickersObj() and not something.TickersObj() ), so the value of this inside it is either the default object ( window in a browser) or undefined (in strict mode). Presumably you are in strict mode.

To create a new instance of a function you have to call it with the new keyword .

var tickersObj = new TickersObj(tag, tag.tickers, tag.lotsOfTags, true, true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM