Parent.call(this, ...)),繼承實例屬性。Child.prototype = new Parent()),繼承原型方法。Child.prototype.constructor = Child)。function Person(name) {
this.name = name;
}
Person.prototype.getName = function () { return this.name; };
function Blogger(name, blog) {
Person.call(this, name); // 步驟 1
this.blog = blog;
}
// 步驟 2 + 3
Blogger.prototype = new Person();
Blogger.prototype.constructor = Blogger;
// 測試
const b = new Blogger('zhenn', 'https://jb51.net');
console.log(b.name); // 'zhenn' (實例屬性)
console.log(b.blog); // 'https://jb51.net' (子類屬性)
console.log(b.getName()); // 'zhenn' (繼承原型方法)
console.log(b instanceof Blogger); // true
console.log(b instanceof Person); // true
上述 new Parent() 會執行父類構造函數,可能產生副作用(如副作用屬性污染原型)。改良:
function inherit(Child, Parent) {
// 建立中介物件,原型指向 Parent.prototype,不執行 Parent 構造函數
const F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.superclass = Parent.prototype; // 可選:便於呼叫 super
}
// 使用
function Person(name) { this.name = name; }
Person.prototype.getName = function () { return this.name; };
function Blogger(name, blog) {
Person.call(this, name);
this.blog = blog;
}
inherit(Blogger, Person);
// 新增子類原型方法
Blogger.prototype.getBlog = function () { return this.blog; };
function extend(Child, Parent, protoProps = {}, staticProps = {}) {
// 1. 原型鏈繼承
const F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.superclass = Parent.prototype;
// 2. 混入原型方法
Object.assign(Child.prototype, protoProps);
// 3. 混入靜態屬性/方法
Object.assign(Child, staticProps);
return Child;
}
// 使用範例
const Animal = function (name) { this.name = name; };
Animal.prototype.speak = function () { console.log(this.name + ' makes a noise'); };
const Dog = extend(function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}, Animal, {
speak() { console.log(this.name + ' barks'); },
getBreed() { return this.breed; }
}, {
DEFAULT_BREED: 'Mixed'
});
const d = new Dog('Buddy', 'Labrador');
d.speak(); // Buddy barks
console.log(Dog.DEFAULT_BREED); // Mixed
class Person {
constructor(name) { this.name = name; }
getName() { return this.name; }
}
class Blogger extends Person {
constructor(name, blog) {
super(name); // 必須先呼叫 super()
this.blog = blog;
}
getBlog() { return this.blog; }
}
const b = new Blogger('zhenn', 'https://jb51.net');
console.log(b.getName()); // zhenn
console.log(b instanceof Person); // true
| 特性 | ES5 寄生組合式 | ES6 Class extends |
|---|---|---|
| 語法 | 手動組合 | 內建關鍵字 |
| super 呼叫 | Parent.call(this) | super() |
| 靜態繼承 | 需手動 Object.assign | 自動繼承 |
| 原型方法定義 | Child.prototype.xxx = ... | class 體內直接寫 |
| 瀏覽器支援 | IE6+ | IE10+ (需 transpile) |
extend 封裝的寄生組合式繼承。init() 方法由調用者控制。