萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

從零手寫 JavaScript 框架核心:DOM 封裝、選擇器、鏈式 API 與模組架構完整教學

jQuery、MooTools、Dojo 等框架背後核心其實不神秘。本文帶你從零實現一個迷你框架 Dome,涵蓋立即執行函數 (IIFE) 封裝、選擇器引擎、DOM 陣列化包裝、鏈式 API 設計、原型方法擴展,讓你真正理解框架運作原理。

第一步:框架骨架 — IIFE 隔離作用域

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('');
$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'

核心設計哲學解析

  1. 類陣列物件:Dome 實例擁有數字索引與 length,可直接 for (let i=0; i<$el.length; i++) 迭代,也支援 Array.from($el)。
  2. 鏈式調用:所有 setter 方法返回 this,getter 返回值。forEach 返回 this,map 返回陣列。
  3. 多元素語意:text() 獲取時,單元素回傳字串,多元素回傳陣列——比 jQuery 直接拼接字串更符合直覺。
  4. 最小依賴:僅依賴 querySelectorAll、classList、addEventListener 等現代原生 API,IE8+ 即可運行(需 Polyfill)。
  5. 擴展性:外掛只需 Dome.prototype.plugin = function() { ...; return this; }。

避坑指南

  • 不要污染 Array.prototype:用 Array.prototype.push.apply(this, els) 而非 this.push(...els)(此時 this 非陣列)。
  • 事件解綁:單頁應用必須提供 off,避免記憶體洩漏。
  • 克隆節點:append/prepend 使用 cloneNode(true),防止同一節點被多處插入導致移動而非複製。
  • 選擇器引擎:生產級框架會用 Sizzle (jQuery) 或自研編譯器支援完整 CSS4,教學用 querySelectorAll 足矣。

擴展練習

  • 實作 parent()、children()、siblings()、closest() 遍歷方法。
  • 實作 animate() 整合 Web Animations API。
  • 實作 ajax() 封裝 fetch,支援攔截器。
  • 加入 TypeScript 定義檔,享受型別提示。

親手寫框架,不只是造輪子,更是重構你對前端架構的認知。當你理解了 $(selector) 背後的每一行代碼,任何框架原始碼都將不再是黑盒。

copyright © 萬盛學電腦網 all rights reserved