萬盛學電腦網

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

JavaScript 原型鏈與面向對象編程深度解析

前言

JavaScript 是基於原型的語言,理解 `prototype`、`constructor`、`__proto__` 及繼承機制是掌握 JS 面向對象的鑰匙。本文通過代碼示例系統講解:構造函數、原型對象、繼承模式、靜態/實例成員、對象字面量等核心概念。

一、構造函數與原型

1. 基本模式

function Person(name) {
  // 實例屬性
  this.name = name;
  
  // 實例方法(不推薦:每個實例創建新函數)
  this.sayName = function() {
    console.log(this.name);
  };
}

// 原型方法(推薦:所有實例共享)
Person.prototype.sayHi = function() {
  console.log('Hi, I am ' + this.name);
};

// 靜態屬性/方法(屬於構造函數本身)
Person.species = 'Human';
Person.createAnonymous = function() {
  return new Person('Anonymous');
};

var p1 = new Person('Alice');
var p2 = new Person('Bob');

p1.sayHi(); // Hi, I am Alice
p2.sayHi(); // Hi, I am Bob

console.log(Person.species); // Human
console.log(Person.createAnonymous().name); // Anonymous

2. 原型鏈圖解


// p1.__proto__ === Person.prototype
// Person.prototype.__proto__ === Object.prototype
// Object.prototype.__proto__ === null

console.log(p1.__proto__ === Person.prototype); // true
console.log(Person.prototype.__proto__ === Object.prototype); // true

二、繼承模式

1. 原型鏈繼承(基礎但有缺陷)

function Parent() {
  this.colors = ['red', 'blue'];
}
Parent.prototype.getColors = function() {
  return this.colors;
};

function Child() {
  // 必須調用父構造函數以繼承實例屬性
  Parent.call(this); // 盜用構造函數
}

// 關鍵:子類原型指向父類實例
Child.prototype = new Parent();
// 修正 constructor 指向
Child.prototype.constructor = Child;

// 新增子類方法
Child.prototype.say = function() {
  console.log('Child');
};

var c1 = new Child();
c1.colors.push('green');
console.log(c1.getColors()); // ['red', 'blue', 'green']

var c2 = new Child();
console.log(c2.getColors()); // ['red', 'blue'] —— 引用類型屬性不再共享

2. 組合繼承(最常用,推薦)

function Parent(name) {
  this.name = name;
  this.friends = ['Mike'];
}
Parent.prototype.sayName = function() {
  console.log(this.name);
};

function Child(name, age) {
  // 繼承實例屬性(第一次調用 Parent)
  Parent.call(this, name);
  this.age = age;
}

// 繼承原型方法(第二次調用 Parent,但不傳參)
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

Child.prototype.sayAge = function() {
  console.log(this.age);
};

var child = new Child('Tom', 10);
child.sayName(); // Tom
child.sayAge();  // 10
console.log(child.friends); // ['Mike'] —— 獨立副本

3. 寄生組合式繼承(完美模式)

function inheritPrototype(subType, superType) {
  var prototype = Object.create(superType.prototype); // 創建對象
  prototype.constructor = subType;                    // 增強對象
  subType.prototype = prototype;                      // 指定對象
}

// 使用
inheritPrototype(Child, Parent);

三、屬性檢測與原型鏈操作

var obj = { a: 1 };
Object.prototype.b = 2;

console.log('a' in obj);           // true(自有+繼承)
console.log(obj.hasOwnProperty('a')); // true(僅自有)
console.log('b' in obj);           // true
console.log(obj.hasOwnProperty('b')); // false

// 遍歷自有屬性
for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    console.log(key, obj[key]);
  }
}

// ES5 靜態方法
console.log(Object.keys(obj)); // ['a']
console.log(Object.getOwnPropertyNames(obj)); // ['a']

四、對象字面量與動態屬性

// 對象字面量
var user = {
  name: 'Jack',
  age: 25,
  greet: function() {
    console.log('Hello, ' + this.name);
  }
};

// 動態添加/刪除
user.email = 'jack@example.com';
delete user.age;

// 方法簡寫(ES6)
var obj = {
  foo() { console.log('foo'); },
  bar: function() { console.log('bar'); }
};

五、常見陷阱與最佳實踐

  1. 原型共享引用類型:在構造函數中初始化數組/對象,不要放在 prototype 上。
  2. constructor 指向錯誤:重寫 prototype 後必須手動修正 `constructor`。
  3. 避免修改內置原型:不要擴展 `Array.prototype`、`Object.prototype` 等,會污染全局環境。
  4. 使用 `Object.create(null)` 創建純字典對象:無原型鏈,避免繼承干擾。
  5. ES6 class 語法糖:本質仍是原型繼承,但語法更清晰,推薦現代項目使用。

六、結語

JavaScript 的原型繼承雖與傳統類繼承不同,但靈活強大。深入理解原型鏈、構造函數、原型對象三者關係,配合組合繼承或 ES6 class,能編寫出清晰、高效、可維護的面向對象代碼。

copyright © 萬盛學電腦網 all rights reserved