jQuery 框架的核心在於從 HTML 文檔中匹配元素並對其執行操作。而它最令人稱道的一點,莫過於能用 $('') 這樣不帶 new 的方式來實例化對象。本文將一步步拆解其背後的實現機制。
使用 jQuery 時,實例化一個 jQuery 對象通常有兩種寫法:
// 無 new 構造
$('#test').text('Test');
// 當然也可以使用 new
var test = new $('#test');
test.text('Test');
大多數人習慣用第一種無 new 的方式,直接 $('') 進行構造,這也是 jQuery 格外便捷之處。當我們使用無 new 構造時,其本質就等同於 new jQuery()。那麼 jQuery 內部是如何做到的呢?先來看源碼:
(function(window, undefined) {
var // ...
jQuery = function(selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context, rootjQuery);
},
jQuery.fn = jQuery.prototype = {
init: function(selector, context, rootjQuery) {
// ...
}
}
jQuery.fn.init.prototype = jQuery.fn;
})(window);
沒看懂也沒關係,我們一步步分析。
在 ECMAScript 中,創建函數最常見的兩種方式是函數表達式和函數聲明。兩者的區別讓不少人感到困惑,因為 ECMA 規範只明確了一點:函數聲明必須帶有標示符(Identifier,也就是函數名稱),而函數表達式則可以省略它。
//函數聲明:
function 函數名稱 (參數:可選){
函數體
}
//函數表達式:
function 函數名稱(可選)(參數:可選){
函數體
}
可見,若不宣告函數名稱,它一定是表達式;但若宣告了名稱,該如何判斷是聲明還是表達式呢?ECMAScript 是透過上下文來區分的:如果 function foo(){} 是作為賦值表達式的一部分,它就是函數表達式;如果它被包含在函數體內,或位於程序最頂部,那就是函數聲明。
function foo(){} // 聲明,因為它是程序的一部分
var bar = function foo(){}; // 表達式,因為它是賦值表達式的一部分
new function bar(){}; // 表達式,因為它是 new 表達式
(function(){
function bar(){} // 聲明,因為它是函數體的一部分
})();
還有一種較少見的函數表達式,就是被括號括住的 (function foo(){}),它是表達式的原因在於括號 () 是一個分組操作符,其內部只能包含表達式。
再回看 jQuery 源碼開頭:
(function(window, undefined) {
/...
})(window)
可以把上面的結構分成兩部分:(function(){window, undefined}) 和 (window)。
第一個 () 是一個表達式,而這個表達式本身是一個匿名函數,因此在這個表達式後面加上 (window) 就表示執行這個匿名函數並傳入參數 window。
先認識一下什麼是原型。在 JavaScript 中,原型也是一個對象,透過原型可以實現對象的屬性繼承。JavaScript 的對象中都包含一個 [[Prototype]] 內部屬性,這個屬性對應的就是該對象的原型。
對於 "prototype" 和 "__proto__" 這兩個屬性,有時容易混淆,「Person.prototype」和「Person.__proto__」是完全不同的。在此簡單介紹:
1. 對於所有對象,都有 __proto__ 屬性,這個屬性對應該對象的原型。
2. 對於函數對象,除了 __proto__ 屬性之外,還有 prototype 屬性。當一個函數被作為構造函數來創建實例時,該函數的 prototype 屬性值將被作為原型賦值給所有對象實例(也就是設置實例的 __proto__ 屬性)。
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.getInfo = function(){
console.log(this.name + " is " + this.age + " years old");
};
//調用
var will = new Person("Will", 28);
will.getInfo();//"Will is 28 years old"
閉包的定義:當一個內部函數被其外部函數之外的變量引用時,就形成了一個閉包。
閉包的作用:在了解閉包的作用之前,先認識 JavaScript 中的 GC 機制:在 JavaScript 中,如果一個對象不再被引用,那麼這個對象就會被 GC 回收,否則這個對象會一直保存在內存中。
在下面的例子中,B 定義在 A 中,因此 B 依賴於 A,而外部變量 c 又引用了 B,所以 A 間接被 c 引用,也就是說 A 不會被 GC 回收,會一直保存在內存中。為證明這個推論,看如下例子:
function A(){
var count = 0;
function B(){
count ++;
console.log(count);
}
return B;
}
var c = A();
c();// 1
c();// 2
c();// 3
count 是 A 中的一個變量,它的值在 B 中被改變,函數 B 每執行一次,count 就在原來的基礎上累加 1,因此 A 中的 count 一直保存在內存中。這就是閉包的作用。有時候我們需要在一個模塊中定義這樣一個變量:希望它一直保存在內存中,又不會「污染」全局變量,這時就可以用閉包來定義這個模塊。
JavaScript 是函數式語言,函數可以實現類,而類是面向對象編程中最基本的概念:
var aQuery = function(selector, context) {
//構造函數
}
aQuery.prototype = {
//原型
name:function(){},
age:function(){}
}
var a = new aQuery();
a.name();
這是常規用法,而 jQuery 顯然不是這樣玩的。若按 jQuery 的書寫方式 $().ready()、$().noConflict() 來看,jQuery 要視為一個類,那麼 $() 就應該返回類的實例才對。於是把代碼改一下:
var aQuery = function(selector, context) {
return new aQuery();
}
aQuery.prototype = {
name:function(){},
age:function(){}
}
透過 new aQuery() 雖然返回的是一個實例,但也能明顯看出問題——死循環了!那麼如何返回一個正確的實例?在 JavaScript 中,實例 this 只跟原型有關系,於是我們可以把 jQuery 類當作一個工廠方法來創建實例,並把這個方法放到 aQuery.prototype 原型中:
var aQuery = function(selector, context) {
return aQuery.prototype.init(selector);
}
aQuery.prototype = {
init:function(selector){
return this;
},
name:function(){},
age:function(){}
}
執行 aQuery() 後,返回的實例如下圖:

很明顯 aQuery() 返回的是 aQuery 類的實例,那麼在 init 中的 this 其實也指向 aQuery 類的實例。問題來了:如果把 init 函數也當作一個構造器,那麼內部的 this 該如何處理?
var aQuery = function(selector, context) {
return aQuery.prototype.init(selector);
}
aQuery.prototype = {
init: function(selector) {
this.age = 18
return this;
},
name: function() {},
age: 20
}
aQuery().age //18
因為 this 只指向 aQuery 類,所以 aQuery 的 age 屬性是可以被修改的。這樣看似沒問題,其實問題很大:
var aQuery = function(selector, context) {
return aQuery.prototype.init(selector);
}
aQuery.prototype = {
init: function(selector) {
if(selector=="a") this.age = 18
return this;
},
name: function() {},
age: 20
}
aQuery("a").age //18
aQuery("b").age //18
當傳入 "a" 時修改了 age=18,於是 aQuery("a").age 為 18;但當傳入 "b" 時並未修改 age,我們希望得到默認值 20,結果卻仍是 18,因為調用 aQuery("a") 時 age 已被改動。這種情況下就出錯了,所以需要設計出獨立的作用域。
看 jQuery 的處理:
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
很明顯,透過實例 init 函數,每次都構建新的 init 實例對象,以此分隔 this,避免相互混淆。我們修改一下代碼:
var aQuery = function(selector, context) {
return new aQuery.prototype.init(selector);
}
aQuery.prototype = {
init: function(selector) {
if(selector=="a") this.age = 18
return this;
},
name: function() {},
age: 20
}
aQuery("a").age //18
aQuery("b").age //undefined
aQuery("a").name() //Uncaught TypeError: Object [object Object] has no method 'name'
又出現新問題:age 變成 undefined,name() 拋出錯誤找不到方法。顯然 new 的 init 與 jQuery 類的 this 分離了。那麼該如何訪問 jQuery 類原型上的屬性與方法呢?關鍵點就在這一行:
// Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn;
我們再改一下:
var aQuery = function(selector, context) {
return new aQuery.prototype.init(selector);
}
aQuery.prototype = {
init: function(selector) {
if(selector=="a") this.age = 18
return this;
},
name: function() { return age; },
age: 20
}
aQuery.prototype.init.prototype = aQuery.prototype;
aQuery("a").age //18
aQuery("b").age //20
aQuery("a").name() //20
最後再看一遍 jQuery 源碼:
(function(window, undefined) {
var // ...
jQuery = function(selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init(selector, context, rootjQuery);
},
jQuery.fn = jQuery.prototype = {
init: function(selector, context, rootjQuery) {
// ...
}
}
jQuery.fn.init.prototype = jQuery.fn;
})(window);
是不是豁然開朗了?大部分人初看 jQuery.fn.init.prototype = jQuery.fn 這一句都會被卡住,很是不解,但這一句堪稱 jQuery 的絕妙之處。分點解析一下:
1)首先要明確,使用 $('xxx') 這種實例化方式時,內部調用的是 return new jQuery.fn.init(selector, context, rootjQuery),也就是構造實例的工作交給了 jQuery.fn.init() 方法完成。
2)將 jQuery.fn.init 的 prototype 屬性設置為 jQuery.fn,那麼使用 new jQuery.fn.init() 生成的對象的原型對象就是 jQuery.fn,因此掛載到 jQuery.fn 上的函數就相當於掛載到 jQuery.fn.init() 生成的 jQuery 對象上,所有用 new jQuery.fn.init() 生成的對象都能訪問到 jQuery.fn 上的所有原型方法。
3)也就是說,實例化方法存在這樣一條關系鏈:
1.jQuery.fn.init.prototype = jQuery.fn = jQuery.prototype ;
2.new jQuery.fn.init() 相當於 new jQuery() ;
3.jQuery() 返回的是 new jQuery.fn.init(),而 var obj = new jQuery(),所以這兩者相當,我們因此可以無 new 實例化 jQuery 對象。
以上就是 jQuery 無 new 構造的全部內容,希望本文對大家學習 jQuery 有所幫助。