Reputation: 235
What is the differences between a normal function and a self invoking anonymous function? And in which cases should i use a self invoking anonymous function? I really dont get the difference between them. And how does i use a SIAF?
Upvotes: 3
Views: 1623
Reputation:
well I am sure the are MANY uses for SIAF! but mainly it is used for namespacing and privacy!
for privacy
var normalkey=89000333;
var privateKey= (function(param){
var secretkey = 123411;
//it is private , nothing outside this function will know of it
var newkey=param+secretkey ;
return newkey
})(normalkey); //passing normalkey as param
you got a privateKey without calling a function to calculate it yourself and the secretkey used to calculate the privateKey is safe inside SIAF.
for namespacing
var fruits= (function() {
return {
name: ["apple", "orange"];
color: [{"red","green"},"orange"]
}
})();
instead of declaring fruitname,fruitcolor.. so on.. in the global namespace, you can get everything from 'fruits'
for the purpose of self-invoking
$(function(){}); //seem familiar? -jquery
Upvotes: 1
Reputation: 4278
A function in Javascript is a first class citizen and can be passed around like an object. When you define a function like so:
function() { ... };
That is all you are doing. Defining it. It is not being used at this point. You can assign it to a variable and call it later on if you wish or pass the variable to another function as an argument.
A self invoking anonymous function is an extremely useful pattern component used for namespacing in Javascript. I prefer to use the more accurate name for it of immediately invoked function expression (IIFE). To understand this pattern I recommend you read up on closures in javascript: How do JavaScript closures work?
(function(namespace, $, undefined){ //undefined is specified here as it can be overwritten in javascript. This ensures we have a true undefined value within our namespace. Make sure not to pass in any argument for this.
var text = "hello world"; // private member
var namespace.text = "hellow world"; //public member
}(window.namespace = window.namespace || {}, jQuery)); //This section calls this function immediately and creates a closure. We pass in the window.namespace argument to give us access to all public member of the namespace.
This provides you with a namespace to avoid global scope pollution and allow you to define private functions and members.
You can find more information here: http://benalman.com/news/2010/11/immediately-invoked-function-expression/
Upvotes: 2