本源碼使用當前的 jQuery 1.3.2 版本,下載時間 2009-4-25,下載地址:點此下載
一個函數
1 /*!
2 * jQuery JavaScript Library v1.3.2
3 * http://jquery.com/
4 *
5 * Copyright (c) 2009 John Resig
6 * Dual licensed under the MIT and GPL licenses.
7 * http://docs.jquery.com/License
8 *
9 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
10 * Revision: 6246
11 */
12 (function(){
4376 })();
省略掉中間的內容,可以看到從第 12 行到 4376 行,jQuery 代碼可以簡化為如上的代碼。
也就是定義了一個匿名的函數,然后執行這個函數。
在這個匿名函數中完成其他的定義和操作,這樣可以避免與系統的其他函數同名造成的命名沖突問題。相當于一個私有的作用域。
$ 是什么?jQuery 又是什么?
13 var
14 // Will speed up references to window, and allows munging its name.
15 window = this,
16 // Will speed up references to undefined, and allows munging its
17 name.
18 undefined,
19 // Map over jQuery in case of overwrite
20 _jQuery = window.jQuery,
21 // Map over the $ in case of overwrite
22 _$ = window.$,
23
24 jQuery = window.jQuery = window.$ = function( selector, context ) {
25 // The jQuery object is actually just the init constructor 'enhanced'
26 return new jQuery.fn.init( selector, context );
27 },
通過這段代碼,可以看到 $,jQuery 是 window 對象上自定義的一個成員,這個成員指向了一個匿名函數,以后可以通過window 對象的 $ 或者 jQuery 來使用這個函數。
這個函數返回了一個通過 jQuery.fn.init 函數定義的對象。說明通過 jQuery 得到的對象其實是一個 jQuery.fn.init 函數創建的對象,那么,以后通過 jQuery.fn.init 的原型定義的函數或者屬性都可以被通過 jQuery 創建的對象來使用。
jQuery.fn 是什么?
35 jQuery.fn = jQuery.prototype = {
538 };
從 35 行到 538 行,為 jQuery.fn 的定義,jQuery.fn 就是 jQuery 所指向的函數的原型對象。所以在 jQuery 的原型上定義的函數就可以通過 jQuery.fn 來使用了。
而上邊的 jQuery.fn.init 就是 jQuery 函數原型對象上的一個函數。
下一篇 如何查看百度聯盟收益(效果報告)