我如何从匿名自调用函数公开函数? [英] how do i expose function from anonymous self invoking function?
问题描述
(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屋!