0

I'm looking to implement something like this:

var settings = (function () {
    this.data = {
        array1: [],
        array2: [],
        array3: []
    };

    this.hasSettings = function () {
            //todo
    };
})();

What I'd like to do with it is:

settings.data.array1.push(item);

Unfortunately i get an:

Uncaught TypeError: Cannot set property 'datas' of undefined

Could someone help me and explain the corrrect way to implement this?

Regards

1
  • this === the outer context. To use the function as a constructor you need to call it with new myFun(),. Instead you are calling it right away. Commented Feb 2, 2015 at 13:12

1 Answer 1

1

white console.log(this) inside your IIFE... this is a window object. To make your code work change IIFE to immediately creating instance:

var settings = new function () {
    this.data = {
        array1: [],
        array2: [],
        array3: []
    };

    this.hasSettings = function () {
            //todo
    };
};

When you write new function(){...}, you immediately call a constructor function with new keyword. The new keyword creates a new object with properties of this and returns it (unless the constructor function returns a non-primitive value).

When you used IIFE, you just populated global object (window in browsers) with properties of this.

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.