萬盛學電腦網

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

JavaScript 原型繼承深度解析:從 __proto__ 到 Object.create 的演進

原型與原型鏈本質

  • 每個**函數**有 prototype 屬性,指向其**原型對象**
  • 每個**對象**有內部槽 [[Prototype]](ES5 可通過 Object.getPrototypeOf()、__proto__ 訪問),指向創建它的構造函數的 prototype
  • 原型對象本身也是對象,也有 [[Prototype]],層層向上直到 Object.prototype (其 [[Prototype]] = null),形成**原型鏈**
  • 關鍵:真正構成查找鏈的是對象的 [[Prototype]],而非函數的 prototype

基本繼承模式:構造函數 + 原型鏈

// 父構造函數
function Parent() {
  this.name = 'parent';
  this.colors = ['red', 'blue']; // 引用類型:共享陷阱
}
Parent.prototype.getName = function() { return this.name; };
Parent.prototype.sharedObj = { a: 1 }; // 原型上共享

// 子構造函數
function Child() {
  this.name = 'child';
  // Parent.call(this); // 組合繼承:調用父構造函數解決實例屬性共享
}

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

var parent = new Parent();
var child = new Child();

console.log(parent.getName()); // "parent"
console.log(child.getName());  // "child" (子實例遮蔽)
// child.colors.push('green'); // ⚠️ 會修改父原型上的共享數組!
// console.log(parent.colors); // ["red", "blue", "green"] 汙染父實例

原型繼承圖解

Parent.prototype (原型對象)
  ├── getName()
  ├── sharedObj {a:1}
  └── [[Prototype]] -> Object.prototype

child (Child 實例)
  ├── name: 'child'
  └── [[Prototype]] -> Parent.prototype

parent (Parent 實例)
  ├── name: 'parent'
  ├── colors: ['red','blue']
  └── [[Prototype]] -> Parent.prototype

寄生組合式繼承(最佳實踐,ES5 標準寫法)

function inherit(Child, Parent) {
  // 1. 創建中介對象:原型指向 Parent.prototype,不調用 Parent 構造函數
  var prototype = Object.create(Parent.prototype);
  // 2. 修正 constructor
  prototype.constructor = Child;
  // 3. 賦值給 Child.prototype
  Child.prototype = prototype;
}

// 使用
function Parent(name) {
  this.name = name;
  this.colors = ['red', 'blue']; // 實例屬性,每個實例獨有
}
Parent.prototype.getName = function() { return this.name; };

function Child(name, age) {
  Parent.call(this, name); // 借用構造函數繼承實例屬性
  this.age = age;
}

inherit(Child, Parent); // 原型繼承方法

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

var child = new Child('child', 18);
console.log(child.getName()); // "child"
console.log(child.sayAge());  // 18
console.log(child.colors);    // ["red","blue"] 獨有副本
child.colors.push('green');
console.log(child.colors);    // ["red","blue","green"] 不影響其他實例

ES5 Object.create() 原型式繼承(無構造函數)

var parent = {
  name: 'parent',
  greet: function() { console.log('Hi, ' + this.name); }
};

// 直接以 parent 為原型創建子對象
var child = Object.create(parent);
child.name = 'child'; // 遮蔽繼承屬性

child.greet(); // "Hi, child"
console.log(child.hasOwnProperty('name')); // true
console.log(parent.isPrototypeOf(child));  // true

// 第二個參數:屬性描述符
var child2 = Object.create(parent, {
  age: { value: 18, writable: true, enumerable: true, configurable: true }
});

ES6 class / extends 糖衣下的原型機制

class Parent {
  constructor(name) {
    this.name = name;
  }
  getName() { return this.name; }
}

class Child extends Parent {
  constructor(name, age) {
    super(name); // 必須先調用 super(),建立 this
    this.age = age;
  }
  sayAge() { return this.age; }
}

// 本質上等同於寄生組合式繼承
// Child.prototype.__proto__ === Parent.prototype
// Child.__proto__ === Parent (靜態方法也繼承)

常見誤區與避坑

原型鏈查找性能

  • 屬性訪問沿原型鏈向上查找,層級越深越慢
  • 熱點代碼可將原型方法「拍平」到實例或緩存到局部變量
  • hasOwnProperty 只檢查自身,不走原型鏈
copyright © 萬盛學電腦網 all rights reserved
誤區後果正確做法
Child.prototype = Parent.prototype父子共享同一原型對象,修改子原型汙染父原型Object.create(Parent.prototype)
忘記 Parent.call(this)實例屬性不繼承,引用類型屬性共享構造函數中調用 Parent.call(this, ...)
不修正 constructorchild.constructor === Parent (false)Child.prototype.constructor = Child
在原型上放引用類型默認值所有實例共享同一對象/數組引用類型放在構造函數 this.x = [] 中