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
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();
精彩评论