jQuery 的 $('div') 為什麼既能當函數調用,又能訪問 length、還能掛原型方法?答案藏在一個不到三十行的 mini 實現裡。自己寫一遍,比看十篇文章都管用。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<script src="js/minijquery.js"></script>
</head>
<body>
<div class="one">1</div>
<div class="two">2</div>
<script>
var result = $('div');
console.log(result);
alert($('div').size());
</script>
</body>
</html>
(function () {
// 暴露給外部引用
var jQuery = window.jQuery = window.$ = function (selector) {
return new jQuery.fn.init(selector);
};
jQuery.fn = jQuery.prototype = {
myjQuery: 'the test one',
length: 0,
size: function () {
return this.length;
},
// 各項選擇器方法的入口
init: function (selector) {
var element = document.getElementsByTagName(selector);
Array.prototype.push.apply(this, element);
return this;
}
};
// 關鍵一步:讓 init 的原型指向 jQuery 的原型
jQuery.fn.init.prototype = jQuery.fn;
})();
第一個關鍵:$ 是一個返回對象的函數
function (selector) { return new jQuery.fn.init(selector); }。調用 $ 時並不是直接執行選擇邏輯,而是 new 出一個 init 實例。這樣 $('div') 的返回值是一個對象,而不是 DOM 節點或數組。
第二個關鍵:init 返回 this
init 裡把 getElementsByTagName 拿到的元素集合 push 到 this 上(this 此時是類數組),然後 return this。這就解釋了為什麼 jQuery 對象既能用 .length 又能用下標訪問——它本質上就是個「長了手腳的數組」。
第三個關鍵:原型鏈的嫁接
jQuery.fn.init.prototype = jQuery.fn; 這一行是整個實現的樞紐。
因為 $ 返回的是 init 的實例,如果什麼都不做,實例只能訪問 init.prototype 上的方法。而我們希望 $('div').size() 能調用 size——size 掛在 jQuery.fn 上,不在 init.prototype 上。把 init.prototype 指向 jQuery.fn(也就是 jQuery.prototype)之後,init 的實例就能沿原型鏈找到 size、myjQuery 這些方法了。
這正是真實 jQuery 源碼裡那句著名註釋的由來:// jQuery.fn.init.prototype = jQuery.fn;。
querySelectorAll。要支持 $('.one')、$('#id'),可以按首字符分派到 getElementsByClassName 或 getElementById。$('div').addClass('a').find('span') 這樣的鏈式調用。這裡的 size 返回的是數字,鏈就斷了。$('li', context) 這種帶上下文的用法。init: function (selector) {
var element = [];
if (selector.charAt(0) === '#') {
var el = document.getElementById(selector.slice(1));
if (el) element.push(el);
} else if (selector.charAt(0) === '.') {
element = document.getElementsByClassName(selector.slice(1));
} else {
element = document.getElementsByTagName(selector);
}
Array.prototype.push.apply(this, element);
return this;
}
把這段加上,一個能處理標簽、class、id 三種最常見選擇器的 mini 版就成型了。
寫完會明白三件事:jQuery 對象為什麼是「類數組」、原型嫁接是怎麼讓實例拿到方法的、以及鏈式調用背後其實只是「每個方法都返回 this」。理解這三點之後,再看任何一個類 jQuery 的庫(Zepto、Cash、或者各家自封裝的 DOM 工具),都能迅速抓住它的骨架。