萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 物件導向完整指南:封裝、繼承、多型、建構函式、原型鏈與 ES6 Class

前言

JavaScript 是基於**原型**的物件導向語言。ES6 引入 `class` 語法糖,但底層仍為原型繼承。理解物件、屬性、方法、建構函式、原型鏈、`this` 綁定是進階開發基石。

核心概念

  • 封裝:將資料(屬性)與行為(方法)包裝在物件內。
  • 聚合/組合:物件持有其他物件參考。
  • 繼承:原型鏈委派,子類存取父類原型方法。
  • 多型:同一介面不同實作(鴨子類型)。

建構函式模式 (ES5)

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

Object.create() 原型式繼承

const animal = {
  breathe() { console.log('breathing'); }
};
const dog = Object.create(animal);
dog.bark = () => console.log('woof');
dog.breathe(); // 繼承自 animal

ES6 Class 語法糖

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 陳述式(已棄用)

with (document) {
  write('Hello'); // 等同 document.write('Hello')
  title = 'New Title';
}
// 嚴格模式禁用,易造成變數解析模糊、效能差,勿使用。

物件屬性描述符 (ES5)

const obj = {};
Object.defineProperty(obj, 'readOnly', {
  value: 42,
  writable: false,
  enumerable: true,
  configurable: false
});
// obj.readOnly = 100; // 嚴格模式拋錯,非嚴格靜默失敗

常見陷阱:this 綁定

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` 丟失。

copyright © 萬盛學電腦網 all rights reserved