I see a lot of this in older JavaScript
(function (w){
w.bar = 'baz';
})(window);
What is the advantage of the above, over
(function(){
window.bar = 'baz';
})();
same goes for any global variable
, or variable defined outside the IIFE
.
An Immediately-invoked Function Expression (IIFE for friends) is a way to execute functions immediately, as soon as they are created. IIFEs are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations.
An IIFE is a good way to secure the scope. You can use IIFEs to prevent global variables' definition issues, alias variables, protect private data, and avoid conflicts of using many libraries that export the same object name.
Self-Invoking function is a type of function that is invoked or called automatically after its definition when followed by the parentheses set () and primarily used for the initialization tasks.
A function's name is the string of characters that come in between the function keyword and the set of parentheses () . The first function has a name, declaredFunction , but the second function, a function expression, does not have a name. The function without a name is called an anonymous function.
In practice there is not much (any?) difference wit the example you have given, but you have probably oversimplified it from the code you are actually looking at.
In a more realistic program, you will have scopes and calls backs which are triggered and run in the eventloop asynchronously, and you are binding the variable to a specific instance in a closure -- so;
(function (w){
setTimeout(function(){w.bar = 'baz';},100);
})(window);
window = window2;
The bar is still being set in the original window, since that is what is bound to w
- where in
(function (){
setTimeout(function(){window.bar = 'baz';},10);
})(window);
window = window2;
It will be set in the instance window2, since that is how the window is bound when the execution of the code eventually happens.
In this example "window" is a global variable, but the same is the case regardless of the scope of the variable that is bound.
mockWindow
for a unit test. Maybe you are using Node.js and you don't have a window
, but want to add to the globals
var instead.p.s. IMO the trivial performance gain mentioned by @Rayon is a red herring.
Passing window is done because local variables are easier and faster to access than global variables ...this may show slight difference in performance . The method really comes in handy with module patterns and/or dependency injection .
Example
var moduleFirst = (function(){
var name = "harry";
return {
firstparam : name
}
})();
var moduleTwo = (function(x){
console.log(x.firstparam);
})(moduleFirst)
Output will be : harry
So when window gets passed in IIFE ; all of its revealed methods are available in a local variable .
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