继承的方法
- 原型继承
- 构造方法继承
- 组合继承
- 原型对象继承
- 寄生继承
- 寄生组合继承
类与继承
现有一个类-猫,然后又想弄一个类-狸花,显然类-狸花除了自己的属性,还包括类-猫的所有的属性的,但我们又不想在定义类-狸花时,重新写一遍类-猫的所有属性,那继承就能很好的达到这样的目的。
js中的类
当我们不使用es6的语法class时,类的属性由构造函数和该类的原型中的属性构成,所以我们要继承一个类时,只要想办法将构造函数和原型中的属性弄到新的类中。
继承
现有一个类Cat
const Cat = function(name){
this.name = name
}
// 是否是动物
Cat.prototype.isAnimal = true
然后要定义一个类Lihua,只需要聚焦类的构造方法和其原型
- 其构造函数中调用类Cat的构造函数
- 其原型指向一个对象,该对象指向Cat的原型
const Lihua = function (name) {
Cat.call(this.name)
// 类-狸花特有属性-强健
this.isStrong = true
}
Lihua.prototype = new Cat()
为什么部直接Lihua.prototype = Cat.prototype呢?
- 因为Cat.prototype也是从别的地方继承过来的
- 如果我们想改Lihua.prototype的属性怎么办?如果是Lihua.prototype = Cat.prototype,那么就会修改了Cat的原型,这明显不合理,我们只是想改Lihua的原型中的属性,不想动Cat的原型。
上面这种继承方式是最常用的继承方式,叫组合继承(组合了原型继承和构造函数继承)
优点是:很高程度实现了类的功能
缺点是Cat这个构造函数调用了两次
寄生组合继承
const genObjConnectProt(){
const Func = function(){}
Func.prototype = Cat.protoType
return new Func()
}
const Lihua = function (name) {
Cat.call(this.name)
// 类-狸花特有属性-强健
this.isStrong = true
}
Lihua.prototype = genObjConnectProt()
这样就只需要调用一次Cat构造函数
使用方式
const meow = new Lihua('meowm')