`
hlbng
  • 浏览: 174616 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

关于 jQuery中 function( window, undefined ) 写法的原因讨论

阅读更多

今天在读 jQuery代码的时候,发现下面的写法:

1
2
3
(function( window, undefined ) {
    ... // code goes here
})(window);

window 肯定是没问题, 表示 BOM 浏览器对象模型中的 window 对象。但是这里为什么会有一个名为 undefined 的形参呢?起初的时候很不理解。去技术群请教了一下,才真正理解了这里的原因。

原来,Javascript 中的 undefined 并不是作为关键字(全部Javascript关键字列表)出现的。因此可以允许用户对其赋值。例如:

1
var undefined = 'myValue';

如此一来,假如 jQuery 中使用下面的写法:

1
2
3
(function( window ) {
    ... // code goes here
})(window);

必然造成中间代码里的 undefined 遭到污染。因为在默认情况下,对于一个未定义的变量,它的值应该是 undefined,假如用户使用形如

1
2
3
4
var undefined = 'myValue';
 
// 或者
window.undefined = 'myValue';

的代码进行赋值,那么,jQuery 中的 undefined 的值就变成了用户指定的值(这里是字符串 ‘myValue’)。这样会造成 jQuery 内部异常。

而 jQuery 采用的这种写法,就很好的避免了这个问题。在执行匿名函数的时候,只传递一个参数 window, 而不传递 undefined,那么函数体中的 undefined 局部变量的值,刚好就是 undefined. 甚为巧妙啊。

-------------------------------------------------------------------------------------------------------------------------------------------------------

//

Use to add a single line comment, or comment out a single line of code.

/* */

Use to add a multi-line comment, or comment out multiple lines of code.

+

Adds two values together or concatenates two strings into a single string.

-

Subtracts the value of a number from another number.

*

Multiples the values of two numbers.

/

Divides a number by another number.

%

Divides a number by another number and returns the remainder.

++

Increments the value of a number by 1.

--

Decrements the value of a number by 1.

- (unary)

Changes the sign of a signed integer.

=

Assigns a value to a variable or other object.

+=

Adds the value of the first item to the second item and assigns the total to the first item as a new value.

-=

Subtracts the value of the second item from the first item and assigns the total to the first item as a new value.

*=

Multiples the value of the first item by the second item and assigns the total to the first item as a new value.

/=

Divides the value of the first item by the second item and assigns the total to the first item as a new value.

>>=

Shifts the first item in binary representation the value of the second item of bits to the right, discarding bits shifted off, and assigns the new value to the first item.

font-weight: bold; font-size: 13px; color: #8f8781; margin-bottom: 0.5em; border-bottom-width: 1px; border-bottom-style: dotted; border-bottom-colo
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics