0

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?

Leon Gaban
  • 27,845
  • 80
  • 281
  • 473
  • Alternatively, you could just return an object with those keys, rather than calling it as a constructor. – Mathletics Aug 05 '15 at 19:18
  • True.. but I have 3 different cases, figured a function to make it would work better in that case? – Leon Gaban Aug 05 '15 at 19:20
  • No, you keep the function, but rather than assigning properties to `this` (making it a constructor) you just return an object, `return { assoTikArray: array, ...}` (making it a factory.) – Mathletics Aug 05 '15 at 19:35

1 Answers1

8

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);
Community
  • 1
  • 1
Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205