mauriblint
mauriblint

Reputation: 1707

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!

Upvotes: 2

Views: 3912

Answers (3)

Guffa
Guffa

Reputation: 700472

You are not even using the property that you have created. Instead you create another global variable with the same name. Use the this keyword to access properties:

var foo = {

  self: null,

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

  doStuff: function() {
    //stuff here
  }

}

(Although saving this in a property is truly pointless...)

If you want a local variable in the object, create a closure for it:

var foo = (function(){

  var self = null;

  return {

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

    doStuff: function() {
      //stuff here
    }
  };

}());

Upvotes: 0

James Clark
James Clark

Reputation: 1811

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.

Upvotes: 6

Pointy
Pointy

Reputation: 413767

You have to use this:

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

edit However, it's still a property of the "foo" object, and it's not super-clear where you're getting instances of "foo" from. In other words, the way your code is written, there's only one object.

Alternatively, you could create your object with a closure:

var foo = function() {
    var self = null;

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

      doStuff: function() {
        //stuff here
      }
    };
}();

Upvotes: 0

Related Questions