JavaScript 沒有類別關鍵字(ES6 前),但函式本身就是物件,天然支援靜態屬性與方法。本文從函式物件本質出發,徹底講解靜態成員定義、呼叫時機、記憶體效能與 ES6 class 語法糖對應關係。
function Bird() {
this.wing = 2; // 實例屬性
this.fly = function() { // 實例方法
alert("我是鳥,我會飛");
}
}
// 函式也是物件,可以直接掛屬性/方法
Bird.jiao = function() {
alert('叽叽喳喳的叫');
};
Bird.jiao(); // 直接呼叫,無需 new Bird()
| 特性 | 靜態成員 | 實例成員 |
|---|---|---|
| 定義位置 | 建構函式本身 Bird.xxx | 建構函式 this.xxx 或 prototype |
| 呼叫方式 | Bird.jiao() | new Bird().fly() |
| this 指向 | 建構函式 Bird | 具體實例物件 |
| 記憶體 | 單一份,全域共享 | 每個實例一份 (prototype 共享方法) |
| 存取實例資料 | 無法直接存取 | 可存取 this 屬性 |
function MathUtil() {} // 僅作為命名空間
MathUtil.PI = 3.1415926535;
MathUtil.random = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
MathUtil.clamp = function(val, min, max) {
return Math.max(min, Math.min(max, val));
};
console.log(MathUtil.random(1, 100)); // 直接呼叫
function Cache() {
if (Cache.instance) return Cache.instance; // 單例守衛
this.data = {};
Cache.instance = this;
}
Cache.get = function(key) {
return Cache.instance?.data[key];
};
Cache.set = function(key, value) {
if (!Cache.instance) new Cache();
Cache.instance.data[key] = value;
};
// 使用
Cache.set('user', { name: 'Tom' });
console.log(Cache.get('user'));
function Widget(config) {
// 判斷是否為靜態呼叫 (未使用 new)
if (!(this instanceof Widget)) {
return Widget.create(config); // 轉向工廠方法
}
// 正常實例化邏輯
this.id = Widget.nextId++;
this.config = config;
}
Widget.nextId = 0; // 靜態計數器
Widget.create = function(config) {
return new Widget(config); // 確保回傳實例
};
// 兩種呼叫方式都能正常運作
var w1 = new Widget({color: 'red'});
var w2 = Widget({color: 'blue'}); // 忘記 new 也沒關係
// ES5 寫法
function Bird() {}
Bird.species = '鳥類';
Bird.fly = function() { console.log('飛行'); };
// ES6 寫法(編譯後本質相同)
class Bird {
static species = '鳥類';
static fly() { console.log('飛行'); }
constructor() {}
}
Bird.fly(); // 兩種寫法效果相同
function Animal() {}
Animal.kingdom = '動物界';
Animal.classify = function() { console.log(this.kingdom); };
function Bird() {}
// 靜態繼承需手動處理
Bird.__proto__ = Animal; // 設定建構函式原型鏈
Bird.classify(); // "動物界" - 靜態方法也能繼承!
console.log(Bird.kingdom); // "動物界"
原理:建構函式的 __proto__ 指向父建構函式,形成靜態成員原型鏈。
this 動態綁定// ❌ 錯誤:試圖在靜態方法存取實例屬性
Bird.wing = 2;
Bird.fly = function() { console.log(this.wing); }; // this 指向 Bird,無 wing 屬性
// ✅ 正確:靜態方法處理類別層級邏輯
Bird.totalCount = 0;
Bird.create = function() {
Bird.totalCount++;
return new Bird();
};
JavaScript 靜態成員本質是「建構函式物件自身的屬性」。善用靜態成員可實現命名空間、單例、工廠、計數器等模式。ES6 static 關鍵字只是語法糖,底層機制完全相同。理解 this 在靜態與實例方法中的不同指向,是避免 Bug 的關鍵。