jQuery、MooTools、Dojo 等框架背後核心其實不神秘。本文帶你從零實現一個迷你框架 Dome,涵蓋立即執行函數 (IIFE) 封裝、選擇器引擎、DOM 陣列化包裝、鏈式 API 設計、原型方法擴展,讓你真正理解框架運作原理。
window.Dome = (function() {
// 私有工具函數
function isArrayLike(obj) {
return obj && typeof obj.length === 'number' && (obj.length - 1) in obj;
}
// 建構函數:包裝原生 DOM 節點/節點列表
function Dome(els) {
// 將類陣列轉為真陣列並掛載到 this (類陣列物件)
Array.prototype.push.apply(this, isArrayLike(els) ? els : [els]);
}
// 公開 API 入口
const dome = {
// 核心選擇器
get: function(selector) {
let els;
if (typeof selector === 'string') {
els = document.querySelectorAll(selector);
} else if (isArrayLike(selector)) {
els = selector; // NodeList、HTMLCollection、陣列
} else {
els = [selector]; // 單一元素
}
return new Dome(els); // 返回 Dome 實例,支援鏈式
},
// 建立元素
create: function(html) {
const div = document.createElement('div');
div.innerHTML = html;
return new Dome(div.children);
}
};
// 原型方法:所有實例共享
Dome.prototype = {
constructor: Dome,
length: 0,
// 核心遍歷:map 返回新陣列,forEach 返回 this (鏈式)
map: function(callback) {
const results = [];
for (let i = 0; i < this.length; i++) {
results.push(callback.call(this, this[i], i));
}
return results;
},
forEach: function(callback) {
this.map(callback);
return this; // 鏈式關鍵
},
// 事件綁定(簡易版)
on: function(event, handler) {
return this.forEach(el => el.addEventListener(event, handler));
},
off: function(event, handler) {
return this.forEach(el => el.removeEventListener(event, handler));
},
// 樣式操作
css: function(prop, value) {
if (typeof prop === 'object') {
return this.forEach(el => Object.assign(el.style, prop));
}
if (value === undefined) {
return this.length ? getComputedStyle(this[0])[prop] : undefined;
}
return this.forEach(el => el.style[prop] = value);
},
// 屬性操作
attr: function(name, value) {
if (value === undefined) {
return this.length ? this[0].getAttribute(name) : undefined;
}
return this.forEach(el => el.setAttribute(name, value));
},
// 內容操作
html: function(html) {
if (html === undefined) {
return this.length ? this[0].innerHTML : undefined;
}
return this.forEach(el => el.innerHTML = html);
},
text: function(txt) {
if (txt === undefined) {
// 核心哲學:多元素回傳陣列,單元素回傳字串
const texts = this.map(el => el.textContent);
return texts.length === 1 ? texts[0] : texts;
}
return this.forEach(el => el.textContent = txt);
},
// DOM 插入
append: function(child) {
const $child = child instanceof Dome ? child : Dome.get(child);
return this.forEach(el => {
$child.forEach(c => el.appendChild(c.cloneNode(true)));
});
},
prepend: function(child) {
const $child = child instanceof Dome ? child : Dome.get(child);
return this.forEach(el => {
$child.forEach(c => el.insertBefore(c.cloneNode(true), el.firstChild));
});
},
// 移除
remove: function() {
return this.forEach(el => el.parentNode && el.parentNode.removeChild(el));
},
// 尋找後代
find: function(selector) {
const found = [];
this.forEach(el => {
found.push(...el.querySelectorAll(selector));
});
return new Dome(found);
},
// 過濾
filter: function(selector) {
return new Dome(this.map(el => el.matches(selector) ? el : null).filter(Boolean));
}
};
return dome;
})();
// 選擇
Dome.get('.container').css('background', '#f0f0f0');
// 鏈式操作
Dome.get('button')
.on('click', () => alert('Clicked!'))
.css({ color: 'white', background: 'blue' })
.append('Appended');
// 建立元素
const $modal = Dome.create('Hello
');
$modal.appendTo = function(target) { // 簡易擴展
Dome.get(target).append(this);
};
$modal.appendTo('body');
// 多元素 text() 行為
console.log(Dome.get('li').text()); // 陣列 ['Item1', 'Item2']
console.log(Dome.get('h1').text()); // 字串 'Title'
Dome 實例擁有數字索引與 length,可直接 for (let i=0; i<$el.length; i++) 迭代,也支援 Array.from($el)。this,getter 返回值。forEach 返回 this,map 返回陣列。text() 獲取時,單元素回傳字串,多元素回傳陣列——比 jQuery 直接拼接字串更符合直覺。querySelectorAll、classList、addEventListener 等現代原生 API,IE8+ 即可運行(需 Polyfill)。Dome.prototype.plugin = function() { ...; return this; }。Array.prototype:用 Array.prototype.push.apply(this, els) 而非 this.push(...els)(此時 this 非陣列)。off,避免記憶體洩漏。append/prepend 使用 cloneNode(true),防止同一節點被多處插入導致移動而非複製。querySelectorAll 足矣。parent()、children()、siblings()、closest() 遍歷方法。animate() 整合 Web Animations API。ajax() 封裝 fetch,支援攔截器。親手寫框架,不只是造輪子,更是重構你對前端架構的認知。當你理解了 $(selector) 背後的每一行代碼,任何框架原始碼都將不再是黑盒。