views:

57

answers:

1

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?

+5  A: 

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();
Tom Bartel
Oh, you are right.Thanks!
Manuel Bitto
Also, the `init` function needs to return `this` so that there is something to put in the `obj` variable.
Guffa
Right, thanks for the clarification Guffa, I've edited my question.
Manuel Bitto
In this case 'var obj =' is not really necessary, is it?
KooiInc
as I see it is already global variable and not necessary here to define var.But if you dont define var in a function, it will be defined in global context so things can go wrong.
mcaaltuntas
@Kooilnc: here *var obj =* is necessary to get obj reference, so we can call it later.
Manuel Bitto