Search code examples
javascriptprivatevarobject-literal

Private var inside Javascript literal object


How can I declare a private var inside a literal object? Becasuse I've this code:

var foo = {

    self: null,

    init: function() {
        self = this;
        self.doStuff();
    },

    doStuff: function() {
        //stuff here
    }

}

This works perfectly, but if I have some objects, the var "self" it will override.. apparently it's a global var.. and I cannot use the restricted word "var" inside this object..

How can I solve this, or make an NameSpace for each object?

Thanks!


Solution

  • You can create a function scope to hide the variable:

    var foo = (function() {
      var self = null
      return {
        init: ...,
        doStuff: ...
      };
    })();
    

    Though it is not clear what self is supposed to do here, and how foo is used.