Reputation: 5253
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
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