4

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?

1 Answer 1

7

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();
Sign up to request clarification or add additional context in comments.

5 Comments

Also, the init function needs to return this so that there is something to put in the obj variable.
Right, thanks for the clarification Guffa, I've edited my question.
In this case 'var obj =' is not really necessary, is it?
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.
@Kooilnc: here var obj = is necessary to get obj reference, so we can call it later.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.