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

后端 未结 5 1370
暗喜
暗喜 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条回答
  •  孤独总比滥情好
    2020-11-22 00:57

    Others have explained undefined. undefined is like a global variable that can be redefined to any value. This technique is to prevent all undefined checks from breaking if someone wrote say, undefined = 10 somewhere. An argument that is never passed is guaranteed to be real undefined irrespective of the value of the variable undefined.

    The reason to pass window can be illustrated with the following example.

    (function() {
       console.log(window);
       ...
       ...
       ...
       var window = 10;
    })();
    

    What does the console log? The value of window object right? Wrong! 10? Wrong! It logs undefined. Javascript interpreter (or JIT compiler) rewrites it this way -

    (function() {
       var window; //and every other var in this function
    
       console.log(window);
       ...
       ...
       ...
       window = 10;
    
    })();
    

    However, if you get the window variable as an argument, there is no var and hence no surprises.

    I don't know if jQuery is doing it, but if you are redefining window local variable anywhere in your function for whatever reason, it is a good idea to borrow it from global scope.

提交回复
热议问题