(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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With