一、原型繼承
function Father() {
this.names = ['tom', 'kevin'];
}
Father.prototype.getName = function () {
console.log(this.names);
}
function Child() {
}
Child.prototype = new Father();
var child1 = new Child();
child1.names.push('boaz'); // ['tom', 'kevin','boaz']
child1.getName();
var child2 = new Child();
child2.getName(); // ['tom', 'kevin','boaz']
原型繼承的缺點:
- 父類的引用類型屬性會被所有子類執行個體共享,任何一個子類執行個體修改了父類的引用類型屬性,其他子類執行個體都會受到影響
- 建立子類執行個體的時候,不能向父類傳參
二、借用構造函數繼承
function Father(name) {
this.name = name;
this.say = function () {
console.log('hello');
}
}
function Child(name) {
this.name = name;
Father.call(this,name);
}
var p1 = new Child('Tom');
console.log('p1', p1);
p1.say();
var p2 = new Child('Kevin');
console.log('p2', p2);
p2.say();
優點:
- 避免了引用類型屬性被所有執行個體共享
- 可以向父類傳參
缺點:
- 方法必須定義在構造函數中
- 每建立一個執行個體都會建立一遍方法
三、組合繼承(原型繼承和借用構造函數繼承的組合)
function Father(name, age) {
this.name = name;
this.age = age;
console.log(this);
}
Father.prototype.say = function() {
console.log('hello');
}
function Child(name,age) {
Father.call(this,name,age);
}
Child.prototype = new Father();
var child = new Child('Tom', 22);
console.log(child);
常用的繼承方式唯一的缺點是,父類的構造函數會被調用兩次
四、寄生式繼承
function createObj(o) {
var clone = object.create(o);
clone.sayName = function () {
console.log('hello');
}
return clone;
}
就是建立一個封裝的函數來增強原有對象的屬性,跟借用構造函數一樣,每個執行個體都會建立一遍方法
五、寄生組合式繼承
// 紅寶書上面的方式
function object(o) {
var F = function() {};
F.prototype = o;
return new F();
}
function inhert(subType,superType) {
var prototype = object(superType.prototype);
// 構造器重定向,如果沒有通過執行個體找回構造函數的需求的話,可以不做構造器的重定向。但加上更嚴謹
prototype.constructor = subType;
subType.prototype = prototype;
}
function Super(name) {
this.name = name;
}
Super.prototype.sayName = function() {
console.log(this.name);
}
function Sub(name, age) {
Super.call(this, name);
this.age = age;
}
inhert(Sub, Super);
var sub = new Sub('Tom', 22);
sub.sayName();
另外一種更容易了解的方式
// 原型+借用構造函數+寄生
function Person() {
console.log(22);
this.class = '人類';
}
// 原型繼承模式
Person.prototype.say = function() {
console.log(this.name);
}
/**
* 寄生 Man.prototype.__proto__ === Person.prototype;
* Man的父親的父親 === Person的父親
*/
Man.prototype = Object.create(Person.prototype);
Man.prototype.constructor = Man;
function Man(name, age) {
this.name = name;
this.age = age;
// 借用構造函數模式
Person.call(this);
}
var man = new Man('張三豐', 100);
console.log(man);
這是es5最好的繼承方式,集合了所有繼承方式的優點于一身。
六、es6的繼承方式
class Father{
constructor(name) {
this.name = name;
}
sayName() {
console.log(this.name);
}
}
class Child extends Father{
constructor(name, age) {
super(name);
this.age = age;
}
}
var child = new Child('Tom',22);
child.sayName();
總結:
三種簡單的繼承方式
- 原型式繼承
- 借用構造函數繼承
- 寄生式繼承
兩種複雜的繼承方式
- 組合式繼承: 1+2的組合
- 寄生組合式繼承: 1+2+3的組合