全域變數污染、命名衝突、程式碼組織混亂是早期 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
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
現代建構工具下,檔案即模組,天然隔離作用域,無需手動命名空間:
// 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),其餘皆在其下。var MyApp = ... 全域掛載。export 導出公開 API。import 具體導出。output.library (若需 UMD 產物)。