原生 JS 基於原型繼承,無 class 關鍵字(ES6 前)。通過工廠函數 Class(def) 模擬類語法,並探討私有變量實現路徑。
function Class(def){
const init = def.initialize || function(){};
const C = function(){ init.apply(this, arguments); };
for(const k in def){
if(k !== 'initialize') C.prototype[k] = def[k];
}
return C;
}
// 使用
const Person = Class({
initialize: function(name){ this.name = name; },
sayHi: function(){ alert('Hi ' + this.name); }
});
new Person('Tom').sayHi();
function Class(def){
const C = def.initialize || function(){};
for(const k in def){
if(k !== 'initialize') C.prototype[k] = def[k];
}
return C;
}
function Class(def){
const priv = def.private || {};
// 提取 initialize 源碼,在 eval 執行形成閉包捕獲 priv
const C = eval('(' + (def.initialize || function(){}).toString() + ')');
for(const k in def){
if(k === 'initialize' || k === 'private') continue;
if(typeof def[k] === 'function'){
C.prototype[k] = eval('(' + def[k].toString() + ')');
}else{
C.prototype[k] = def[k];
}
}
return C;
}
// 使用
const Person = Class({
private: { height: 160, weight: 50 },
initialize: function(name, h, w){
this.name = name;
_.height = h || _.height; // _ 指向 priv
_.weight = w || _.weight;
},
show: function(){ alert(this.name + ' ' + _.height + ' ' + _.weight); }
});
new Person('Jerry').show();
class Person { #height; constructor(){this.#height=160} } 原生私有、零成本、標準化。const priv = new WeakMap(); priv.set(this, {h:160}); ES5 可用、無 eval、無內存洩漏。function Person(){ const h=160; this.getH=()=>h; } 簡單直接,每實例一份副本。理解「模擬類」演進歷史有助於掌握 JS 物件模型本質。現代項目請直接使用 ES6 Class + #私有字段或 TypeScript private,工程化、可維護、標準化。