继承的几种方式?实现原理?
function Animal (name) {
this.name = name || 'Animal'
this.sleep = function(){
console.log(this.name + '正在睡觉!')
}
}
Animal.prototype.eat = function(food) {
console.log(this.name + '正在吃:' + food)
}
- 1.原型链继承
原理:子类的原型对象 = 父类的实例
特点:基于原型链,既是父类的实例,也是子类的实例
缺点:无法实现多继承
function Cat(){}
Cat.prototype = new Animal()
Cat.prototype.name = 'Tom'
var cat = new Cat()
console.log(cat.name)
console.log(cat.eat('fish'))
console.log(cat.sleep())
console.log(cat instanceof Animal)
console.log(cat instanceof Cat)
- 2.构造继承
原理:使用 call方法 将父类的构造函数来增强子类实例,等于是复制父类的实例属性给子类 (没用到原型)
特点:可以实现多继承
缺点:只能继承父类实例的属性和方法,不能继承原型上的属性和方法 cat.eat(‘fish’)报错
function Cat(name){
Animal.call(this)
this.name = name || 'Tom'
}
var cat = new Cat('jerry')
console.log(cat.name)
console.log(cat.sleep())
console.log(cat instanceof Animal)
console.log(cat instanceof Cat)
- 3.实例继承 (原型式继承)
优点:简单,易实现,可以继承实例属性/方法,也可以继承原型属性/方法
缺点:不能多次继承
function Cat(name){
var instance = new Animal()
instance.name = name || 'Tom'
return instance
}
var cat = new Cat('jerry')
console.log(cat.name)
console.log(cat.eat('fish'))
console.log(cat.sleep())
console.log(cat instanceof Animal)
console.log(cat instanceof Cat)
- 4.组合继承:相当于构造继承和原型链继承的组合体
原理:通过调用父类构造,继承父类的属性并保留传参的优点,然后通过将父类实例作为子类原型,实现函数复用
特点:可以继承实例属性/方法,也可以继承原型属性/方法
缺点:调用了两次父类构造函数,生成了两份实例
function Cat(name){
Animal.call(this)
this.name = name || 'Tom'
}
Cat.prototype = new Animal()
Cat.prototype.constructor = Cat
var cat = new Cat('jerry')
console.log(cat.name)
console.log(cat.eat('fish'))
console.log(cat.sleep())
console.log(cat instanceof Animal)
console.log(cat instanceof Cat)
- 5.寄生组合继承
原理:通过寄生方式,砍掉父类的实例属性,这样,在调用两次父类的构造的时候,就不会初始化两次实例方法/属性
优点:通过寄生的方式来修复组合式继承的不足,完美的实现继承
function Cat(name){
Animal.call(this)
this.name = name || 'Tom'
}
(function(){
var Super = function(){}
Super.prototype = Animal.prototype
Cat.prototype = new Super()
})();
var cat = new Cat('jerry')
console.log(cat.name)
console.log(cat.eat('fish'))
console.log(cat.sleep())
console.log(cat instanceof Animal)
console.log(cat instanceof Cat)