萬盛學電腦網

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

深度解析 JavaScript 原型鏈:從函數對象到繼承實現

核心認知:JS 沒有類,只有函數

JavaScript 是基於原型的語言。函數同時具備兩種角色:

  1. 普通函數調用:fn()
  2. 構造函數調用:new Fn(),創建實例並建立原型鏈

函數創建時發生了什麼?

function A() { this.name = 'A'; }
// 1. 創建函數對象 A(可調用)
// 2. 創建原型對象 @A(A.prototype 指向它)
// 3. A.prototype.constructor === A
// 4. 實例 a1 = new A() 內部有 [[Prototype]] 指向 @A

圖解:A.prototype → @A ← a1.__proto__

原型屬性共享驗證

function A() { this.name = 'A'; }
var a1 = new A();
A.prototype.age = 1;
alert(a1.age); // 1 ← 通過原型鏈訪問
alert(a1.__proto__ === A.prototype); // true (現代瀏覽器)

原型鏈尋找規則

  1. 在實例自身屬性中查找。
  2. 沿 __proto__ 指向原型對象查找。
  3. 繼續向上直到 Object.prototype(頂層)。
  4. 找到返回值,否則 undefined。

繼承實現:子構造函數原型指向父實例

function A() { this.name = 'A'; }
function B() { this.age = 1; }
B.prototype = new A(); // 關鍵:B.prototype 是 A 的實例
alert(new B().name); // 'A' ← 繼承成功

為什麼不直接 B.prototype = A.prototype?

  • 若修改 B.prototype.x = 1,會污染 A.prototype,導致父子耦合。
  • 使用 new A() 創建中間對象,隔離父子原型,修改子原型不影響父原型。

ES5 經典繼承模式(組合繼承)

function Parent(name) { this.name = name; }
Parent.prototype.say = function() { console.log(this.name); };

function Child(name, age) {
  Parent.call(this, name); // 借用構造函數繼承實例屬性
  this.age = age;
}
Child.prototype = Object.create(Parent.prototype); // 原型鏈繼承方法
Child.prototype.constructor = Child; // 修正 constructor

jQuery 源碼啟示:無 new 調用的秘密

var $ = jQuery = function(selector, context) {
  return new init(selector, context); // 內部 new,外部無感
};
jQuery.fn = jQuery.prototype = { size: function() { return this.length; } };
function init(selector, context) { /* ... */ }
init.prototype = jQuery.fn; // init 實例共享 jQuery.fn 方法

用戶寫 $('div') 實際調用工廠函數,返回 init 實例,實例擁有 jQuery.fn 上的所有方法,實現「無 new 也能鏈式調用」。

總結

  • 函數 prototype 指向原型對象,原型對象 constructor 指回函數。
  • 實例 __proto__ 指向構造函數的 prototype。
  • 原型鏈 = 多個 __proto__ 串聯,頂端為 Object.prototype。
  • 繼承本質:子構造函數的原型 = 父構造函數的實例(或 Object.create(父原型))。
  • 現代開發推薦 class 語法糖,底層仍是原型機制。
copyright © 萬盛學電腦網 all rights reserved