JavaScript 是基於**原型**的物件導向語言。ES6 引入 `class` 語法糖,但底層仍為原型繼承。理解物件、屬性、方法、建構函式、原型鏈、`this` 綁定是進階開發基石。
function Book(title, author) {
this.title = title;
this.author = author;
}
Book.prototype.getInfo = function() {
return `${this.title} by ${this.author}`;
};
const myBook = new Book('JS Guide', 'Author');
console.log(myBook.getInfo()); // "JS Guide by Author"
console.log(myBook instanceof Book); // true
console.log(myBook.constructor === Book); // true
const animal = {
breathe() { console.log('breathing'); }
};
const dog = Object.create(animal);
dog.bark = () => console.log('woof');
dog.breathe(); // 繼承自 animal
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
getInfo() { return `${this.title} by ${this.author}`; }
static createFromJSON(json) { return new Book(json.title, json.author); }
}
class EBook extends Book {
constructor(title, author, fileSize) {
super(title, author);
this.fileSize = fileSize;
}
getInfo() { return `${super.getInfo()} (${this.fileSize}MB)`; } // 覆寫
}
with (document) {
write('Hello'); // 等同 document.write('Hello')
title = 'New Title';
}
// 嚴格模式禁用,易造成變數解析模糊、效能差,勿使用。
const obj = {};
Object.defineProperty(obj, 'readOnly', {
value: 42,
writable: false,
enumerable: true,
configurable: false
});
// obj.readOnly = 100; // 嚴格模式拋錯,非嚴格靜默失敗
const obj = {
value: 42,
getValue() { return this.value; }
};
const fn = obj.getValue;
console.log(fn()); // undefined (this 指向 window/undefined)
// 修正
const bound = obj.getValue.bind(obj);
console.log(bound()); // 42
// 或箭頭函式
const obj2 = {
value: 42,
getValue: () => this.value // 詞法綁定外層 this (需注意模組/全域作用域)
};
掌握「原型鏈委派」機制是理解 JS 物件導向的鑰匙。現代代碼優先使用 `class`、`extends`、`super`、`Object.create()`,配合 `Object.defineProperty`/`Proxy` 實現精細控制。避免 `with`、避免在迴圈建立函式、小心 `this` 丟失。