JS中7种实现继承方式

146 阅读1分钟

一、 原型链式继承: 将父类的实例作为子类的原型

// 定义一个父类型
function Animal (name) { 
this.name = name;
this.say = function(){ console.log(I’m this.name); } 
} 
// 原型对象方法
Animal.prototype.eat = function(food) { 
console.log(this.name + '正在吃:' + food); 
};
function Cat(){ } 
Cat.prototype = new Animal(); 
Cat.prototype.name = 'cat’;
var cat = new Cat();

缺点:创建子类实例时,无法向父类构造函数传参

二、 构造函数继承

// 定义一个父类型
function Animal (name) { 
this.name = name;
this.say = function(){ console.log(I’m this.name); } 
} 
// 原型对象方法
Animal.prototype.eat = function(food) { 
console.log(this.name + '吃:' + food); 
};
function Cat(name,age){
Animal.call(this,name);
this.age = age;
}
var cat = new Cat();

三、实例继承

// 定义一个父类型
function Animal (name) { 
this.name = name;
this.say = function(){ console.log(I’m this.name); } 
} 
// 原型对象方法
Animal.prototype.eat = function(food) { 
console.log(this.name + '吃:' + food); 
};
function Cat(name,age){
var o = new Animal(name); //先创建子类型实例
o.age = age;
return o;
}
var cat = new Cat();

四、拷贝继承

// 定义一个父类型
function Animal (name) { 
this.name = name;
this.say = function(){ console.log(I’m this.name); } 
} 
// 原型对象方法
Animal.prototype.eat = function(food) { 
console.log(this.name + '吃:' + food); 
};
function Cat(name,age){ 
var animal = new Animal(name); 
for(var p in animal){ 
Cat.prototype[p] = animal[p]; 
} 
this.age = age
} 
var cat = new Cat();

缺点:无法获取父类不可for in遍历的方法

五、 组合继承

// 定义一个父类型
function Animal (name) { 
this.name = name;
this.say = function(){ console.log(I’m this.name); } 
} 
// 原型对象方法
Animal.prototype.eat = function(food) { 
console.log(this.name + '吃:' + food); 
};
function Cat(name,age){ 
Animal.call(this,name); 
this.age = age
} 
Cat.prototype = new Animal(); 
Cat.prototype.constructor = Cat; 
var cat = new Cat();

六、寄生组合继承

// 定义一个父类型
function Animal (name) { 
this.name = name;
this.say = function(){ console.log(I’m this.name); } 
} 
// 原型对象方法
Animal.prototype.eat = function(food) { 
console.log(this.name + '吃:' + food); 
};
function Cat(name,age){ Animal.call(this,name); this.age = age } 
(function(){ // 创建一个没有实例方法的类
var Super = function(){}; 
Super.prototype = Animal.prototype; //将实例作为子类的原型
Cat.prototype = new Super(); 
})(); 
var cat = new Cat();

七、 ES6 class extends继承

Class 父类型{
constructor(){
}… }
Class 子类型 extends 父类型{
constructor(){
super();
} }