Thursday 7 April 2016

Immediately invoked function expressions (IIFEs)

//IIFEs - Immediately invoked function expressions
//IIFEs don't pollute the global environment.
(function(){
 console.log('Executed!');
})();
//*************************************************************
/* We can move the last pair of parenthesis () before the semicolon inside the parenthesis containing hte whole function. This works the same way as the
code snippet given above. 
*/
(function(){
 console.log('Executed again!');
}());
//*************************************************************
//IIFEs don't pollute the global environment.
(function(){
 var employeeName = 'Jack';
})();
/* The linew of code below will give error as employeeName has been declared
with keyword var inside the function so it does not pollute the global 
namespace. Its scope is limited to the function only. */

/* console.log(employeeName);//Uncaught ReferenceError: employeeName is not defined
*/
//*************************************************************
/* app in the code below is an object that is empty here but in a real
app it will be populated. Most of the libraries in js has
a global variable e.g., $ in jQuery. An application has often a variable
in the global namespace called app. */
var app = {};
(function (ns) {
 ns.name = 'None';
})(app);//Passing the global variable app as an argument to the IIFE function.
console.log(app.name);//None
//*************************************************************
var app = {};
var jQuery = {};
/* The way we pass jQuery as a second argument to the IIFE guarantees that
the jQuery === $ (the dollar sign). */
(function (ns, $) {
 ns.name = 'None';
  console.log($ === jQuery);//true
})(app, jQuery);
//*************************************************************
/* To make sure that the system's undefined object is set to the undefined 
object we do as given below: */
var app = {};
var jQuery = {};
(function (ns, $, undefined) {
 ns.name = 'None';
  console.log(undefined);//undefined
})(app, jQuery);
//*************************************************************
//We can also use +, -, or ! with the keyword function instead of parentheses
+function(){
 var employeeName = 'Jack';
  console.log('Executed!');//Executed
}();
console.log(employeeName);//Uncaught ReferenceError: employeeName is not defined.
//*************************************************************

No comments:

Post a Comment