**實例** 是通過構造函數 (或 `class`)、使用 `new` 操作符創建出的**具體對象**。它擁有類定義的所有屬性結構與方法行為,但持有**獨立的狀態數據**。
// 1. 定義類 (構造函數)
function Car(brand, color) {
this.brand = brand;
this.color = color;
this.drive = function() { console.log(this.brand + ' running'); };
}
// 2. 實例化
var myCar = new Car('Tesla', 'Red'); // myCar 是 Car 的一個實例
var yourCar = new Car('BMW', 'Blue'); // yourCar 是另一個實例
// 3. 實例特徵
console.log(myCar.brand); // 'Tesla' - 獨立狀態
console.log(yourCar.brand); // 'BMW' - 互不影響
myCar.drive(); // 'Tesla running'
console.log(myCar instanceof Car); // true - 類型標識
| 特性 | 說明 |
|---|---|
| 獨立性 | 每個實例擁有自己的屬性副本 (引用類型屬性指向同一對象除非重新賦值) |
| 共享方法 | 方法通常定義在 `prototype` 上,所有實例共享同一函數對象,節省內存 |
| 類型檢查 | `instanceof` 操作符檢查構造函數的 `prototype` 是否在實例原型鏈上 |
| 構造器引用 | 實例 `.constructor` 指向創建它的構造函數 |
class Car {
constructor(brand, color) {
this.brand = brand;
this.color = color;
}
drive() { console.log(this.brand + ' running'); }
}
const myCar = new Car('Tesla', 'Red'); // 實例
**實例 = `new Constructor()` 產出的對象**。它是面向對象編程中「對象」的具體體現,承載數據狀態,響應方法調用。理解「類/構造函數 → 實例化 → 實例」三部曲,是掌握 JS 面向對象的基石。