// 1. 構造函數:定義實例屬性
function Person(name, age) {
this.name = name;
this.age = age;
}
// 2. 原型:定義共享方法/屬性
Person.prototype = {
constructor: Person, // 修正 constructor 指向
getName: function() { return this.name; },
getAge: function() { return this.age; },
// 共享屬性(慎用,引用類型會被所有實例共享)
// skills: [] // 危險!所有實例共用同一數組
};
// 3. 實例化
var p1 = new Person('Alice', 25);
var p2 = new Person('Bob', 30);
console.log(p1.getName()); // "Alice"
console.log(p2.getAge()); // 30
console.log(p1.getName === p2.getName); // true (共享同一函數)
p1 ──────► Person.prototype ──────► Object.prototype ──────► null
│ │
│ ├─ getName()
│ ├─ getAge()
│ └─ constructor: Person
│
├─ name: "Alice"
└─ age: 25
Person.prototype.sex = '男'; // 為所有實例添加默認屬性
var p3 = new Person('Charlie', 28);
console.log(p3.sex); // "男" (來自原型)
p3.sex = '保密'; // 實例添加同名屬性,遮蔽原型
console.log(p3.sex); // "保密"
delete p3.sex; // 刪除實例屬性
console.log(p3.sex); // "男" (恢復讀取原型)
function Animal(name) {
this.name = name;
}
Animal.prototype.say = function() { console.log(this.name + ' makes 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.bark = function() { console.log(this.name + ' barks'); };
var dog = new Dog('Buddy', 'Golden');
dog.say(); // "Buddy makes sound" (來自 Animal.prototype)
dog.bark(); // "Buddy barks" (來自 Dog.prototype)
console.log(dog instanceof Dog, dog instanceof Animal); // true true
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
getName() { return this.name; }
getAge() { return this.age; }
static species = 'Human'; // 靜態屬性
}
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // 必須先調用 super()
this.grade = grade;
}
study() { console.log(this.name + ' studying'); }
}
const s = new Student('Tom', 20, 'Senior');
console.log(s.getName()); // "Tom"
s.study(); // "Tom studying"
| 方案 | 實現 | 優缺點 |
|---|---|---|
| 閉包 (ES5) | 構造函數內 var 私有變量,特權方法訪問 | 真私有、每實例獨立函數副本(內存開銷) |
| Symbol 唯一鍵 | const _name = Symbol(); this[_name] = name; | 非真私有(可遍歷 Symbol),但避免意外訪問 |
| WeakMap | const _data = new WeakMap(); _data.set(this, {name}); | 真私有、無內存洩漏、需 ES6 |
| #私有字段 (ES2022) | class { #name; constructor(n){this.#name=n;} } | 原生真私有、語法清晰、現代瀏覽器全支援 |
class BankAccount {
#balance = 0; // 私有字段
#transactions = []; // 私有數組
constructor(owner) {
this.owner = owner; // 公共屬性
}
deposit(amount) {
if (amount <= 0) throw new Error('金額需大於0');
this.#balance += amount;
this.#transactions.push({type: 'deposit', amount, time: Date.now()});
}
withdraw(amount) {
if (amount > this.#balance) throw new Error('餘額不足');
this.#balance -= amount;
this.#transactions.push({type: 'withdraw', amount, time: Date.now()});
}
getBalance() { return this.#balance; }
getStatement() {
return this.#transactions.map(t => `${t.type}: ${t.amount}`);
}
}
const acc = new BankAccount('Alice');
acc.deposit(1000);
acc.withdraw(200);
console.log(acc.getBalance()); // 800
// acc.#balance; // SyntaxError: Private field '#balance' must be declared in an enclosing class
class Config {
static API_URL = 'https://api.example.com';
static getHeaders() { return { 'Content-Type': 'application/json' }; }
}
class AdminConfig extends Config {
static ADMIN_TOKEN = 'secret';
}
// 子類繼承父類靜態成員
console.log(AdminConfig.API_URL); // "https://api.example.com"
console.log(AdminConfig.getHeaders()); // { 'Content-Type': 'application/json' }
prototype.items = [] 導致所有實例共享Constructor.prototype.constructor = ConstructorJavaScript 通過「構造函數 + 原型」實現了基於原型的繼承,ES6 Class 為其提供了語法糖,ES2022 私有字段彌補了最後一塊拼圖。理解原型鏈查找、this 綁定、屬性遮蔽、繼承本質,是寫出高質量 JS 面向對象代碼的基石。