How can I open a function from an anonymous call function?

(function(){ var a = function () { alert("hey now!! "); }; return {"hi":function(){return a;}}; })(); hi(); 

This code does not work. How can I open a function?

+6
source share
7 answers

The self invoking function returns an object with the hi property, this object is not added to the global scope, so you can directly use the property. Put the result of the function in a variable:

 var o = (function(){ var a = function (){ alert("hey now!! "); }; return {"hi":function(){return a;}}; })(); 

Using a property to call a function will only return the function contained in variable a , so you need to call the return value from the function to call the function containing the warning:

 o.hi()(); 

Demo: http://jsfiddle.net/Guffa/9twaH/

+5
source

There are two main ways:

 var MyNameSpace = (function(){ function a (){ alert("hey now!! "); }; return {a: a}; })(); MyNameSpace.a(); 

or

 (function(){ function a (){ alert("hey now!! "); }; MyNameSpace = {a: a}; })(); MyNameSpace.a(); 

I prefer the second way as it seems cleaner

It is called the "exponential module template", which you can read to better understand :)

https://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript

+3
source
  var obj = (function(){ var a= function (){ alert("hey now!! "); }; return {"hi":function(){return a;}}; })(); obj.hi() 
0
source

You must assign the return value of the anonymous function to a variable in the current scope:

 var f = (function() { var a = function() { alert("hey now!! "); }; return { "hi": function() { return a; } }; })(); f.hi()(); 
0
source

 (function(){ var a = function () { alert("hey now!! "); }; return {"hi":function(){return a;}}; })().hi()(); 
0
source

I believe that in order to expose a function, instead of its code, the syntax should be

 var obj2 = (function(){ var a= function (){ alert("hey now!! "); }; return {"hi":a}; })(); alert(obj2.hi()); 
0
source

Or you could wrap your hello function in IIFE, for example ...

 var myFunction = (function(){ var a = function () { alert("hey now!! "); }; return { "hi": (function(){ return a; }()) }; })(); myFunction.hi(); 
0
source

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


All Articles