萬盛學電腦網

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

JavaScript 實作命名空間模式:從簡單物件到模組化架構

為什麼需要命名空間?

全域變數污染、命名衝突、程式碼組織混亂是早期 JS 開發痛點。命名空間提供邏輯分組、避免衝突、利於維護。

模式一:單一全域物件 (最基礎)

var MyApp = MyApp || {};

MyApp.Models = MyApp.Models || {};
MyApp.Views = MyApp.Views || {};
MyApp.Controllers = MyApp.Controllers || {};
MyApp.Utils = MyApp.Utils || {};

// 定義類別
MyApp.Models.User = function(name) {
    var _name = name; // 私有變數 (閉包)
    this.getName = function() { return _name; };
    this.setName = function(name) { _name = name; };
};

MyApp.Models.User.prototype = {
    greet: function() { console.log('Hello, ' + this.getName()); }
};

// 使用
var user = new MyApp.Models.User('Alice');
user.greet(); // Hello, Alice

模式二:立即執行函式 (IIFE) 封裝私有狀態

MyApp.Utils.DateHelper = (function() {
    // 私有常數/函式
    var WEEKDAYS = ['日','一','二','三','四','五','六'];
    function pad(n) { return n < 10 ? '0'+n : ''+n; }
    
    // 公開 API
    return {
        format: function(date, fmt) {
            var o = { YYYY: date.getFullYear(), MM: pad(date.getMonth()+1), DD: pad(date.getDate()), HH: pad(date.getHours()), mm: pad(date.getMinutes()), ss: pad(date.getSeconds()), W: WEEKDAYS[date.getDay()] };
            return fmt.replace(/YYYY|MM|DD|HH|mm|ss|W/g, m => o[m]);
        },
        parse: function(str) { /* ... */ }
    };
})();

// 使用
MyApp.Utils.DateHelper.format(new Date(), 'YYYY-MM-DD');

模式三:動態命名空間建立器 (通用工具)

function namespace(nsString) {
    var parts = nsString.split('.'), parent = window, current = '';
    for (var i = 0; i < parts.length; i++) {
        current = parts[i];
        parent[current] = parent[current] || {};
        parent = parent[current];
    }
    return parent;
}

// 使用
var util = namespace('MyApp.Utils.Storage');
util.set = function(key, val) { localStorage.setItem(key, JSON.stringify(val)); };
util.get = function(key) { return JSON.parse(localStorage.getItem(key)); };

// 現在可用 MyApp.Utils.Storage.set/get

模式四:CommonJS / ES Modules 現代替代 (建議)

現代建構工具下,檔案即模組,天然隔離作用域,無需手動命名空間:

// src/models/User.js
export class User {
    constructor(name) { this._name = name; }
    getName() { return this._name; }
    greet() { console.log(`Hello, ${this._name}`); }
}

// src/utils/date.js
export function format(date, fmt) { /* ... */ }

// 使用
import { User } from './models/User.js';
import { format } from './utils/date.js';

命名空間別名技巧 (簡化深層路徑)

// 檔案頂部或模組內
const NS = MyApp.Controllers.UserManagement;
const UserModel = MyApp.Models.User;

// 甚至解構
const { User, Role } = MyApp.Models;
const { format, parse } = MyApp.Utils.DateHelper;

避坑指南

  • 重複宣告檢查:var MyApp = MyApp || {} 確保多檔案載入順序不影響。
  • 不要在迴圈/函式內重複建立命名空間:效能與可讀性雙失。
  • 避免過深層級:MyApp.Modules.User.Profile.Settings.Preferences 太長,考慮拆分模組檔案。
  • 全域污染最小化:只暴露一個根命名空間 (如 MyApp),其餘皆在其下。

從命名空間遷移到 ES Modules 清單

  1. 移除 var MyApp = ... 全域掛載。
  2. 每個檔案使用 export 導出公開 API。
  3. 使用端改為 import 具體導出。
  4. 建構工具設定 output.library (若需 UMD 產物)。
copyright © 萬盛學電腦網 all rights reserved