想真正搞懂 jQuery,最直接的方式是自己刻一個迷你版。這個練習只實作最核心的兩件事:用 $() 取得元素,以及用 extend 合併物件設定。寫完你會發現,jQuery 的「魔法」其實一點都不神秘。
(function (window) {
var arr = [];
var VP = function (selector, context) {
return new VP.fn.init(selector, context);
};
VP.fn = VP.prototype = {
constructor: VP,
init: function (selector, context) {
var _document = window.document,
elem,
mark = selector.charAt(0);
// 目前只支援 #id 選擇器
if (mark == '#') {
elem = _document.getElementById(selector.substring(1));
if (elem) {
this[0] = elem;
this.length = 1;
}
}
return this;
},
splice: arr.splice,
};
// 靜態與原型共用同一份 extend
VP.extend = VP.fn.extend = function () {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// 支援 extend(true, target, obj) 這種深拷貝呼叫
if (typeof target === "boolean") {
deep = target;
target = arguments[i] || {};
i++;
}
if (typeof target !== "object" && !VP.isFunction(target)) {
target = {};
}
if (i === length) {
target = this;
i--;
}
for (; i < length; i++) {
if ((options = arguments[i]) != null) {
for (name in options) {
src = target[name];
copy = options[name];
if (target === copy) continue;
if (deep && copy && (VP.isPlainObject(copy) || (copyIsArray = VP.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && VP.isArray(src) ? src : [];
} else {
clone = src && VP.isPlainObject(src) ? src : {};
}
target[name] = VP.extend(deep, clone, copy);
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
};
// 原型方法:取出第 0 個元素
VP.fn.extend({
get: function () {
return this[0];
},
});
// 關鍵一步:讓 init 的原型指向 VP.fn,new 出來的物件才帶有这些方法
VP.fn.init.prototype = VP.fn;
window.VP = VP;
})(window);
1. 為什麼要 VP.fn.init.prototype = VP.fn?
$('#app') 實際上是呼叫 new VP.fn.init(...),new 出來的物件原型是 init.prototype。把它指向 VP.fn,等於讓所有實例共用同一組方法,這就是 jQuery「同一套原型」的核心手法。
2. 為什麼要 return this?
init 回傳 this,new 表達式才會拿到這個被擴充了 length 與索引屬性的物件,而不是一個空的 init 實例。
3. 為什麼用 IIFE 包起來?
(function(window){ ... })(window) 建立獨立作用域,內部變數不會污染全域,只把 VP 掛到 window 上對外公開。
4. extend 的 deep 參數。
深拷貝會遞迴合併巢狀物件, jQuery 的 $.extend(true, {}, a, b) 就是這個邏輯;淺拷貝則是直接覆寫。實作插件時,把使用者傳入的 options 合併到預設值上,靠的就是它。
這個迷你版只做到 #id 選擇器與物件合併,距離真正的 jQuery 還很遠(還缺 class 選擇、鏈式方法、事件綁定、DOM 操作等),但骨架已經完整。想繼續練習的話,建議下一步就補上 getElementsByClassName 支援與 each 方法。