我如何从匿名自调用函数公开函数? [英] how do i expose function from anonymous self invoking function?

查看:90
本文介绍了我如何从匿名自调用函数公开函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

hi();

这段代码不起作用。我如何公开一个功能?

解决方案

自调用函数返回一个包含属性 hi 的对象,此对象不会添加到全局范围,以便您可以直接使用该属性。将函数的结果放入一个变量中:

pre $ var $ o
(function(){

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

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

})();

使用该属性来调用函数将只返回变量 a ,所以你必须调用函数的返回值来调用包含alert的函数:

  o.hi()(); 

演示: http://jsfiddle.net/Guffa/9twaH/


 (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/

这篇关于我如何从匿名自调用函数公开函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆