Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i expose function from anonymous self invoking function?

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

 hi();

This code doesn' t work. How do i expose a function??

like image 970
DrStrangeLove Avatar asked Sep 22 '11 10:09

DrStrangeLove


2 Answers

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

var o =
(function(){

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

  return {"hi":function(){return a;}};

})();

Using the property to call the function will only return the function contained in the variable a, so you have to call the return value from the function to call the function that contains the alert:

o.hi()();

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

like image 161
Guffa Avatar answered Nov 10 '22 18:11

Guffa


There are two basic 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 2nd way since it seems cleaner

It is called the "revealing module pattern" btw, which you can read up on to understand it better :)

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

like image 36
Martin Jespersen Avatar answered Nov 10 '22 19:11

Martin Jespersen