Leon Gaban
Leon Gaban

Reputation: 39018

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

enter image description here

Thoughts on what I'm doing wrong?

Upvotes: -1

Views: 45

Answers (1)

Quentin
Quentin

Reputation: 943100

You are simply calling the function without context (i.e. 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);

Upvotes: 8

Related Questions