亂糟糟的屬性、方法、巢狀循環讓代碼只有上帝能讀懂。OO 能帶來:
// 建立空對象
const bill = {};
// 動態添加屬性/方法
bill.name = "Bill E Goat";
bill.sound = function() { console.log("bahhh!"); };
// 一次性定義(推薦)
const bill = {
name: "Bill E Goat",
sound() { console.log("bahhh!"); } // ES6 方法簡寫
};
// 訪問
bill.name; // "Bill E Goat"
bill.sound(); // "bahhh!"
bill["name"]; // 非合法標識符屬性名必須用括號
bill.sayName = function() {
console.log("Hello " + this.name);
};
bill.sayName(); // "Hello Bill E Goat"
const sayName = bill.sayName;
sayName(); // "Hello undefined" —— this 丟失!指向 window/undefined
教訓:方法被提取為獨立函數調用時,this 指向改變。
function Game(title) {
this.title = typeof title !== "undefined" ? title : "";
}
// 建立實例
const zelda = new Game("Legend of Zelda");
const smb = new Game("Super Mario Brothers");
zelda.title; // "Legend of Zelda"
smb.title; // "Super Mario Brothers"
// 動態添加實例方法
zelda.loveTitle = function() {
console.log("I love " + this.title);
};
zelda.loveTitle(); // "I love Legend of Zelda"
{}this 指向新物件this(除非显式返回物件)Game.prototype.heartIt = function() {
console.log("I heart " + this.title);
};
zelda.heartIt(); // "I heart Legend of Zelda"
smb.heartIt(); // "I heart Super Mario Brothers"
// 原型鏈查找:zelda → Game.prototype → Object.prototype → null
所有實例共享同一個 heartIt 函數,節省記憶體。
function RPG(title, level) {
Game.call(this, title); // 繼承屬性
this.level = level;
}
// 繼承原型方法
RPG.prototype = Object.create(Game.prototype);
RPG.prototype.constructor = RPG; // 修正 constructor
RPG.prototype.grind = function() {
this.level++;
console.log(this.title + " level up to " + this.level);
};
const ff7 = new RPG("Final Fantasy VII", 1);
ff7.heartIt(); // 繼承自 Game.prototype
ff7.grind(); // "Final Fantasy VII level up to 2"
class Game {
constructor(title = "") {
this.title = title;
}
heartIt() {
console.log("I heart " + this.title);
}
}
class RPG extends Game {
constructor(title, level) {
super(title); // 必須先呼叫 super()
this.level = level;
}
grind() {
this.level++;
console.log(`${this.title} level up to ${this.level}`);
}
}
const eldenRing = new RPG("Elden Ring", 1);
eldenRing.heartIt(); // "I heart Elden Ring"
eldenRing.grind(); // "Elden Ring level up to 2"
Class 底層仍是原型繼承,但語法更清晰、不易出錯。
class / extends(ES6+)prototype/類體中,不在構造函數內this 閉包陷阱,必要時用箭頭函數綁定:this.handleClick = () => { ... }const user = { ...authMixin, ...logMixin }Object.freeze()、const、readonly (TS)