一、原型繼承
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']
原型繼承的缺點(diǎn):
- 父類的引用類型屬性會(huì)被所有子類實(shí)例共享,任何一個(gè)子類實(shí)例修改了父類的引用類型屬性,其他子類實(shí)例都會(huì)受到影響
- 創(chuàng)建子類實(shí)例的時(shí)候,不能向父類傳參
二、借用構(gòu)造函數(shù)繼承
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();
優(yōu)點(diǎn):
- 避免了引用類型屬性被所有實(shí)例共享
- 可以向父類傳參
缺點(diǎn):
- 方法必須定義在構(gòu)造函數(shù)中
- 每創(chuàng)建一個(gè)實(shí)例都會(huì)創(chuàng)建一遍方法
三、組合繼承(原型繼承和借用構(gòu)造函數(shù)繼承的組合)
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);
常用的繼承方式唯一的缺點(diǎn)是,父類的構(gòu)造函數(shù)會(huì)被調(diào)用兩次
四、寄生式繼承
function createObj(o) {
var clone = object.create(o);
clone.sayName = function () {
console.log('hello');
}
return clone;
}
就是創(chuàng)建一個(gè)封裝的函數(shù)來增強(qiáng)原有對(duì)象的屬性,跟借用構(gòu)造函數(shù)一樣,每個(gè)實(shí)例都會(huì)創(chuàng)建一遍方法
五、寄生組合式繼承
// 紅寶書上面的方式
function object(o) {
var F = function() {};
F.prototype = o;
return new F();
}
function inhert(subType,superType) {
var prototype = object(superType.prototype);
// 構(gòu)造器重定向,如果沒有通過實(shí)例找回構(gòu)造函數(shù)的需求的話,可以不做構(gòu)造器的重定向。但加上更嚴(yán)謹(jǐn)
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();
另外一種更容易理解的方式
// 原型+借用構(gòu)造函數(shù)+寄生
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;
// 借用構(gòu)造函數(shù)模式
Person.call(this);
}
var man = new Man('張三豐', 100);
console.log(man);
這是es5最好的繼承方式,集合了所有繼承方式的優(yōu)點(diǎn)于一身。
六、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();
總結(jié):
三種簡(jiǎn)單的繼承方式
- 原型式繼承
- 借用構(gòu)造函數(shù)繼承
- 寄生式繼承
兩種復(fù)雜的繼承方式
- 組合式繼承: 1+2的組合
- 寄生組合式繼承: 1+2+3的組合