Manuel Bitto
Manuel Bitto

Reputation: 5253

Is possible to initialize an object in javascript in this way?

I'd like to initialize an object in javascript calling directly a method that belongs to it:

  var obj = (function(){
      return{
          init: function(){
              console.log("initialized!");
              return this;
          },
          uninit: function(x){
              console.log("uninitialized!");
          }
      };
  }).init();

  //later
  obj.uninit();
  obj.init();

This specific example doesn't work, is there something similar?

Upvotes: 4

Views: 2125

Answers (1)

Tom Bartel
Tom Bartel

Reputation: 2258

EDIT: init() returns this, thanks Guffa.

You're only defining an anonymous function, but not actually calling it. To call it right away, add a pair of parentheses:

var obj = (function(){
  return{
      init: function(){
          console.log("initialized!");
          return this;
      },
      uninit: function(x){
          console.log("uninitialized!");
      }
  };
})().init();

Upvotes: 7

Related Questions