JavaScript的继承方式
function animal(name = "animal"){
this.name = name;
this.sleep = function(){
console.log(this.name + '睡觉了' );
}
} //父类
animal.prototype.eat = function(food){
console.log(this.name + '正在吃' + food);
}
一、原型链继承
将父亲的实例作为子类的原型
function Cat(){
Cat.prototype = new animal();
Cat.prototype.name = 'Cat';
}
二、构造继承
使用父类的构造函数来增强子类实例,等于赋值父类的实例属性给子类
function Cat(name = 'Tom'){
animal.call(this);
this.name = name;
}
可以实现多继承,只是继承父类的实例属性和方法,不能继承原型属性/方法
三、实例继承
为父类实例添加新特性,作为子类实例返回
function Cat(name = 'Tom'){
var instance = new animal();
instance.name = name
return instance;
}
实例是父类的实例,不是子类的
四、拷贝继承
function Cat(name = 'Tom'){
var animal = new animal();
for(var p in animal){
Cat.prototype[p] = animal[p];
}
Cat.prototype.name = name;
}
需要枚举,受限,效率低
五、组合继承
通过调用父类的构造,继承父类的属性并保留传参的优点,然后通过把父类实例作为子类原型,实现函数复用
function People(name,age){
this.name = name || 'wangxiao'
this.age = age || 27
}
People.prototype.eat = function(){
return this.name + this.age + 'eat sleep'
}
function Woman(name,age){
People.call(this,name,age)
}
Woman.prototype = new People();
Woman.prototype.constructor = Woman;
let wonmanObj = new Woman(ren,27);
wonmanObj.eat();
六、寄生组合继承
//父类
function People(name,age){
this.name = name || 'wangxiao'
this.age = age || 27
}
//父类方法
People.prototype.eat = function(){
return this.name + this.age + 'eat sleep'
}
//子类
function Woman(name,age){
//继承父类属性
People.call(this,name,age)
}
//继承父类方法
(function(){
// 创建空类
let Super = function(){};
Super.prototype = People.prototype;
//父类的实例作为子类的原型
Woman.prototype = new Super();
})();
//修复构造函数指向问题
Woman.prototype.constructor = Woman;
let womanObj = new Woman();