JavaScript 雖無傳統類別 (ES6 前),但透過**建構函式** + **原型鏈** 完整實現物件導向。本文示範建構函式定義屬性/方法、建立實例、動態存取屬性、原型方法優化,並對照 ES6 `class` 語法糖。
function Person(name, age) {
// 1. 定義實例屬性 (每個實例獨擁)
this.name = name;
this.age = age;
// 2. 定義實例方法 (每個實例會建立獨立函式副本 - 記憶體浪費)
this.showInfo = function() {
alert("name: " + this.name + " -- age: " + this.age);
};
}
// 3. 實例化
var zhangSan = new Person("張三", 30);
// 4. 存取屬性:點標記法 vs 括號標記法
console.log("Name:", zhangSan["name"], ", Age:", zhangSan.age);
// 括號標記法允許動態屬性名:zhangSan[variableKey]
// 5. 呼叫方法
zhangSan.showInfo(); // alert: "name: 張三 -- age: 30"
所有實例共享同一個方法函式,節省記憶體:
function Person(name, age) {
this.name = name;
this.age = age;
}
// 方法定義在 prototype 上
Person.prototype.showInfo = function() {
console.log("Name: " + this.name + ", Age: " + this.age);
};
Person.prototype.sayHello = function() {
console.log("Hello, I'm " + this.name);
};
var p1 = new Person("張三", 30);
var p2 = new Person("李四", 25);
p1.showInfo(); // Name: 張三, Age: 30
p2.sayHello(); // Hello, I'm 李四
console.log(p1.showInfo === p2.showInfo); // true - 同一個函式引用
p1 --> Person.prototype --> Object.prototype --> null
| (showInfo, sayHello) (toString, hasOwnProperty...)
|
+-- name: "張三"
+-- age: 30
var person = new Person("王五", 28);
// 動態屬性名
var prop = "name";
console.log(person[prop]); // "王五"
// 檢測自身屬性 vs 繼承屬性
console.log(person.hasOwnProperty('name')); // true (自身)
console.log(person.hasOwnProperty('showInfo')); // false (來自 prototype)
console.log('showInfo' in person); // true (包含繼承)
// 列舉自身可列舉屬性
for (var key in person) {
if (person.hasOwnProperty(key)) {
console.log(key + ': ' + person[key]);
}
}
// 輸出: name: 王五, age: 28
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
// 實例方法 (自動定義在 prototype)
showInfo() {
console.log(`Name: ${this.name}, Age: ${this.age}`);
}
sayHello() {
console.log(`Hello, I'm ${this.name}`);
}
// 靜態方法 (屬於類別本身)
static species() {
return 'Homo sapiens';
}
// Getter/Setter
get birthYear() {
return new Date().getFullYear() - this.age;
}
set birthYear(year) {
this.age = new Date().getFullYear() - year;
}
}
// 使用
const person = new Person("趙六", 35);
person.showInfo(); // Name: 趙六, Age: 35
console.log(person.birthYear); // 1990 (getter)
person.birthYear = 1985; // setter
console.log(person.age); // 40
Person.species(); // "Homo sapiens"
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + ' makes a sound');
};
function Dog(name, breed) {
Animal.call(this, name); // 繼承實例屬性
this.breed = breed;
}
// 關鍵:建立原型鏈,不呼叫 Animal 建構式
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog; // 修正 constructor 指向
Dog.prototype.speak = function() {
console.log(this.name + ' barks! (' + this.breed + ')');
};
const dog = new Dog('旺財', '柴犬');
dog.speak(); // 旺財 barks! (柴犬)
class Animal {
constructor(name) { this.name = name; }
speak() { console.log(this.name + ' makes a sound'); }
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 必須先呼叫 super()
this.breed = breed;
}
speak() {
super.speak(); // 可選:呼叫父方法
console.log(this.name + ' barks! (' + this.breed + ')');
}
}
const dog = new Dog('旺財', '柴犬');
dog.speak();
// 旺財 makes a sound
// 旺財 barks! (柴犬)
| 錯誤 | 後果 | 正確做法 |
|---|---|---|
| 方法寫在建構式內 | 每實例佔用獨立函式記憶體 | 方法放 `prototype` 或用 `class` |
| 忘記 `new` 呼叫建構式 | `this` 指向全域污染變數 | 慣例首字大寫、文檔標註、或用 `if (!(this instanceof Person)) return new Person(...)` |
| 直接修改 `prototype` 物件 | 破壞 `constructor` 指向 | `Object.create(Parent.prototype)` + 修正 `constructor` |
| 箭頭函式做方法 | 無 `this` 綁定,無法存取實例屬性 | 一般函式或 `class` 方法語法 |