JavaScript 是基於原型的語言。函數同時具備兩種角色:
fn()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 (現代瀏覽器)
__proto__ 指向原型對象查找。Object.prototype(頂層)。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() 創建中間對象,隔離父子原型,修改子原型不影響父原型。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
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 語法糖,底層仍是原型機制。