最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how do i expose function from anonymous self invoking function? - Stack Overflow

programmeradmin9浏览0评论
 (function(){
   var a = function () {
     alert("hey now!! ");
   };
   return {"hi":function(){return a;}};
 })();

 hi();

This code doesn' t work. How do i expose a 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??

Share Improve this question edited Sep 22, 2011 at 12:52 Andrew D. 8,2303 gold badges23 silver badges24 bronze badges asked Sep 22, 2011 at 10:57 DrStrangeLoveDrStrangeLove 11.6k16 gold badges63 silver badges72 bronze badges
Add a ment  | 

7 Answers 7

Reset to default 7

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./resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript

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/Guffa/9twaH/

 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());

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();
发布评论

评论列表(0)

  1. 暂无评论