How does this JavaScript/jQuery syntax work: (function( window, undefined ) { })(window)?

后端 未结 5 1445
暗喜
暗喜 2020-11-22 00:30

Have you ever taken a look under the hood at the jQuery 1.4 source code and noticed how it\'s encapsulated in the following way:

(function(          


        
5条回答
  •  萌比男神i
    2020-11-22 01:11

    window is passed in like that just in case someone decides to redefine the window object in IE, I assume the same for undefined, in case it's re-assigned in some way later.

    The top window in that script is just naming the argument "window", an argument that's more local that the global window reference and it what the code inside this closure will use. The window at the end is actually specifying what to pass for the first argument, in this case the current meaning of window...the hope is you haven't screwed up window before that happens.

    This may be easier to think of by showing the most typical case used in jQuery, plugin .noConflict() handling, so for the majority of code you can still use $, even if it means something other than jQuery outside this scope:

    (function($) {
      //inside here, $ == jQuery, it was passed as the first argument
    })(jQuery);
    

提交回复
热议问题