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

I would like to initialize an object in javascript calling the method directly belonging 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 does not work, is there something similar?

+4
source share
1 answer

EDIT: init() returns this , thanks Guffa.

You define an anonymous function, but don't really name 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(); 
+7
source

Source: https://habr.com/ru/post/1309864/


All Articles