-1

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?

3
  • Alternatively, you could just return an object with those keys, rather than calling it as a constructor. Commented Aug 5, 2015 at 19:18
  • True.. but I have 3 different cases, figured a function to make it would work better in that case? Commented Aug 5, 2015 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.) Commented Aug 5, 2015 at 19:35

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.