简体   繁体   中英

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??

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/

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

Or you could wrap your 'hi' function in an IIFE like so...

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

 })();

 myFunction.hi();
 var obj = (function(){

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

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

 })();

 obj.hi()

You have to 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()();

It?

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

I suppose in order to expose the function, instead of its code, the syntax should be

var obj2 = (function(){

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

 return {"hi":a};

 })();

alert(obj2.hi());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM