$() 不需要 new?jQuery 採用「建構函數 + 原型」模式,但巧妙隱藏了 new 操作:
var jQuery = function(selector, context) {
return new jQuery.fn.init(selector, context, rootjQuery);
};
jQuery.fn = jQuery.prototype = { ... };
jQuery.fn.init.prototype = jQuery.fn; // 關鍵:init 原型指向 jQuery.fn
$(selector) 像呼叫函式,實則回傳 init 實例。init.prototype = jQuery.fn 使所有實例共享 jQuery.prototype 上的方法(css, on, find...)。jQuery.fn,自動對所有實例生效。document.querySelectorAll / Sizzle 引擎查找 DOM。DOMContentLoaded / ready。this(類陣列),擁有 length、context、selector 等屬性。單一 jQuery() 函式根據參數類型/個數執行不同邏輯:
$(selector) 查找元素$(htmlString) 建立元素$(callback) 綁定 ready$(element) 包裝原生 DOM$(arrayLike) 包裝類陣列這正是 JavaScript 動態語言特性(參數不固定、類型不固定)賦予的多態表現力。
jQuery.fn.init.prototype = jQuery.fn = jQuery.prototype
↑ ↑
實例 __proto__ 所有實例共享方法
這條原型鏈連接,讓 init 實例擁有 jQuery 所有原型方法,同時保有 constructor 指向 init。