(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 badges7 Answers
Reset to default 7There 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();