1

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);
Fabii
  • 3,820
  • 14
  • 51
  • 92
  • 2
    I don't think they'd behave any differently. But I don't think it's a good idea to have a variable (or function parameter) with the same name as a built-in object like `window`. – nnnnnn Jan 09 '15 at 06:00
  • 1
    http://stackoverflow.com/questions/2716069/how-does-this-javascript-jquery-syntax-work-function-window-undefined http://stackoverflow.com/questions/5020479/what-advantages-does-using-functionwindow-document-undefined-windo – epascarello Jan 09 '15 at 06:03
  • 1
    Normally you do it like `(function(w){ })(window);` so you have a different variable to reference. You will see this in some minimzer scripts. If you do jQuery development, you are supposed to follow the pattern for plugins. `(function($){ })(jQuery);` Why? because of noConflict mode. – epascarello Jan 09 '15 at 06:05

2 Answers2

3

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.

Community
  • 1
  • 1
Ingo Bürk
  • 19,263
  • 6
  • 66
  • 100
1
(function(window){
})(window);
  1. Now when you pass window (window); here, this is the window object, global one.

  2. This is a local copy of the window created for that function.

    (function(window){ })

  3. 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.

Naeem Shaikh
  • 15,331
  • 6
  • 50
  • 88