What is the difference between the following two code snippets ? I've seen both used in module patters, closures and higher level function declaration. What it the proper use for both ?
(function(){
})();
(function(window){
})(window);
What is the difference between the following two code snippets ? I've seen both used in module patters, closures and higher level function declaration. What it the proper use for both ?
(function(){
})();
(function(window){
})(window);
The semantic difference is small in this case. However, if window
is used a lot throughout the code, aliasing it as a local variable allows for better minification.
(function (window) { window['foo'] = window['baz']; })(window);
can be minified to
(function(w){w['foo']=w['baz']})(window)
Without the local alias, window
could not be reduced and the minification would instead be
(function(){window['foo']=window['baz']})()
There are other reasons as well as other use-cases for similar tricks. Have a look at this question to find more in-depth explanations.
(function(window){
})(window);
Now when you pass window (window);
here, this is the window object, global one.
This is a local copy of the window created for that function.
(function(window){
})
when you do this ,
(function(window){
console.log(window.x)
})
you are refering to the local copy not the global one, but still they only hold the reference to the global window object, so eventually you are still accessing the default window object.
So there is no change in behavior, but window object is locally copied.