萬盛學電腦網

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

JavaScript 面向對象與原型鏈全解析:從工廠模式到 ES6 Class 的演進之路

三種創建對象模式演進

1. 簡單對象字面量

var box = { name: 'lee', age: 100, run: function() { return this.name + this.age + '運行中...'; } };
console.log(box.run());
// 缺點:大量相似對象代碼重複,無類型標識

2. 工廠模式

function createObject(name, age) {
  var obj = new Object();
  obj.name = name; obj.age = age;
  obj.run = function() { return this.name + this.age + '運行中...'; };
  return obj;
}
var box1 = createObject('lee', 100);
var box2 = createObject('jack', 200);
// 缺點:無法識別對象類型(typeof 皆為 Object)

3. 構造函數模式(解決類型識別)

function Box(name, age) {
  this.name = name; this.age = age;
  this.run = function() { return this.name + this.age + '運行中...'; };
}
var box1 = new Box('lee', 100);
var box2 = new Box('jack', 200);
console.log(box1 instanceof Box); // true
// 缺點:每個實例擁有獨立 run 函數,內存浪費

原型模式:共享方法的關鍵

function Box() {}
Box.prototype.name = 'Lee';
Box.prototype.age = 100;
Box.prototype.run = function() { return this.name + this.age + '運行中...'; };

var box1 = new Box();
var box2 = new Box();
console.log(box1.run === box2.run); // true,共享同一函數引用

原型鏈訪問規則

  1. 先找實例自身屬性/方法
  2. 再沿 __proto__ 找構造函數 prototype
  3. 再找 Object.prototype,最後 null

關鍵屬性與方法

  • __proto__:實例指向原型的內部指針(IE 不支援直接訪問)
  • constructor:原型指回構造函數
  • isPrototypeOf():判斷原型鏈關係
  • hasOwnProperty(prop):判斷屬性是否在實例自身
  • in 操作符:實例或原型鏈中存在即返回 true

屬性遮蔽與刪除

box1.name = 'Jack'; // 實例新增 name,遮蔽原型 name
delete box1.name;   // 刪除實例屬性,恢復讀取原型值

組合模式:構造函數定義屬性 + 原型定義方法(業界標準)

function Box(name, age) {
  this.name = name; this.age = age; // 實例屬性(私有)
}
Box.prototype = {
  constructor: Box, // 修正 constructor 指向
  run: function() { return this.name + this.age + '運行中...'; },
  say: function() { console.log('hello'); }
};

動態原型模式 / 寄生構造函數 / 穩妥構造函數

(篇幅所限略過,核心思想:延遲初始化原型、封裝私有變量、無 this 依賴)

繼承模式總覽

模式核心思想缺點
原型鏈繼承Child.prototype = new Parent()引用類型屬性共享、無法向父傳參
借用構造函數Parent.call(this, args)方法無法復用(在構造函數內定義)
組合繼承原型鏈繼承方法 + 借用構造函數繼承屬性調用兩次父構造函數
原型式繼承Object.create(proto)同原型鏈,引用類型共享
寄生式繼承創建對象→增強→返回方法無法復用
寄生組合式繼承Object.create(Parent.prototype) + 借用構造函數**最佳實踐**(ES5)

ES6 Class 語法糖(本質仍是原型)

class Box {
  constructor(name, age) { this.name = name; this.age = age; }
  run() { return this.name + this.age + '運行中...'; }
  static createDefault() { return new Box('default', 0); } // 靜態方法
}

class SpecialBox extends Box {
  constructor(name, age, power) {
    super(name, age); // 必須先調用 super()
    this.power = power;
  }
  run() { return super.run() + ' [增強版]'; } // 覆寫並調用父方法
}

總結

理解「構造函數 + 原型」是 JS 面向對象的基石。實戰中:

  1. 屬性寫在構造函數,方法寫在原型
  2. 繼承用 **寄生組合式**(ES5)或 **extends**(ES6+)
  3. 慎用 __proto__,改用 Object.getPrototypeOf/Object.setPrototypeOf
  4. 利用 Object.create(null) 創建純字典對象,避免原型污染
copyright © 萬盛學電腦網 all rights reserved