01
When reading jQuery code today, I found the following statement:
02
(Function (window, undefined ){
03
... // Code goes here
04
}) (Window );
05
Window must be okay, indicating the window object in the BOM browser object model. But why is there a parameter named undefined? It was hard to understand at first. I went to the Technical Group to ask why.
06
Originally, undefined in Javascript does not appear as a keyword (list of all Javascript keywords. Therefore, users can assign values to them. For example:
07
Varundefined = 'myvalue ';
08
In this way, we assume that jQuery uses the following statement:
09
(Function (window ){
10
... // Code goes here
11
}) (Window );
12
This will inevitably cause the undefined in the intermediate code to be contaminated. By default, the value of an undefined variable is undefined.
13
Varundefined = 'myvalue ';
14
// Or
15
Window. undefined = 'myvalue ';
16
The undefined value in jQuery is changed to the value specified by the user (here is the string 'myvalue '). This will cause jQuery internal exceptions.
17
18
JQuery can avoid this problem. When an anonymous function is executed, only one window parameter is passed without undefined. The undefined local variable value in the function body is just undefined.
19
20
Compare the following code:
21
22
<Script type = "text/javascript">
23
(Function (window, undefined ){
24
Alert (undefined );
25
}) (Window );
26
</Script>
27
28
<Script type = "text/javascript">
29
Var undefined = 'myvalue ';
30
(Function (window ){
31
Alert (undefined );
32
}) (Window );
33
</Script>
34
35
<Script type = "text/javascript">
36
Var undefined = 'myvalue ';
37
(Function (window, undefined ){
38
Alert (undefined );
39
}) (Window );
40
</Script>
41
42
<Script type = "text/javascript">
43
Var undefined = 'myvalue ';
44
Window. undefined = 'myvalue _ 2 ′;
45
(Function (window ){
46
Alert (undefined );
47
}) (Window );
48
</Script>
49
50
<Script type = "text/javascript">
51
Var undefined = 'myvalue ';
52
Window. undefined = 'myvalue _ 2 ′;
53
(Function (window, undefined ){
54
Alert (undefined );
55
}) (Window );
56
</Script>
Author: leon_lau