文章引用經典圖解(見原文圖片),清晰展示 Function.prototype、Object.prototype、實例 __proto__、建構函式 prototype 之間的關係網。

prototype,JS 引擎查找屬性時沿此鏈向上搜尋。Firefox/Chrome 可直接存取,IE 不支援。var Person = function() {};
var p = new Person();
// 等價於:
var p = {}; // 1. 建立空物件
p.__proto__ = Person.prototype; // 2. 連結原型
Person.call(p); // 3. 建構函式執行,this 指向 p
驗證:p.__proto__ === Person.prototype // true
own property)查找。__proto__ 向上追溯:Person.prototype → Object.prototype → null。undefined。var Person = function() {};
Person.prototype.sayName = function() { alert('My Name is Jacky'); };
Person.prototype.age = 27;
var p = new Person();
p.sayName(); // 彈出 "My Name is Jacky"
console.log(p.age); // 27,從原型鏈取得
function Animal(name) { this.name = name; }
Animal.prototype.speak = function() { console.log(this.name + ' makes a sound'); };
function Dog(name) { Animal.call(this, name); }
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.speak = function() { console.log(this.name + ' barks'); };
var d = new Dog('Buddy');
d.speak(); // "Buddy barks"
console.log(d instanceof Animal); // true
console.log(d instanceof Dog); // true
class Animal {
constructor(name) { this.name = them; }
speak() { console.log(this.name + ' makes a sound'); }
}
class Dog extends Animal {
speak() { console.log(this.name + ' barks'); }
}
底層仍是原型鏈機制,class 只是更易讀的宣告式語法。