1.原型链继承
–>通过原型链,继承属性和方法
function SuperType () {
this.colors = ['pink', 'blue']
this.name = 'qrq'
}
SuperType.prototype.getName = function () {
return this.name
}
function SubType() {
this.age = '20'
}
SubType.prototype = new SuperType()
SubType.prototype.getAge = function() {
console.log(this.age)
}
SubType.prototype.constructor = SubType //更改constructor指向
let instance1 = new SubType()
instance1.colors.push('yello')
instance1.getName() //'qrq'
instance1.colors // ['pink', 'blue', 'yello']
let instance2 = new SubType()
instance2.colors // ['pink', 'blue', 'yello']
- 缺点:
1.通过原型链继承,原型会变成另一个类型的实例,该原型的引用类型属性被所有实例共享
2.在创建子类实例时,没有办法在不影响所有对象实例的情况下给超类型的构造函数中传递函数
2.借用构造函数
function SuperType (name) {
this.colors = ['pink', 'blue']
this.name = name
}
SuperType.prototype.say = function() {
return this.name
}
function SubType(name) {
SuperType.call(this, name)
}
let instance1 = new SubType('yxq')
instance1.colors.push('yello') // ['pink', 'blue', 'yello']
let instance2 = new SubType('ce')
instance2.colors //['pink', 'blue']
- 优点:
1.可以向超类传递参数
2.解决原型中包含引用类型值被所有实例共享的问题
- 缺点:
1.方法都在构造函数中定义,函数无法复用
2.无法继承超类型定义的方法
3.组合继承
–> 通过原型链及构造函数实现继承
function SuperType (name) {
this.colors = ['pink', 'blue']
this.name = name
}
SuperType.prototype.say = function() {
return this.name
}
function SubType(name) {
SuperType.call(this, name)
}
SubType.prototype = new SuperType()
SubType.construtor = SubType
let instance1 = new SubType('yxq')
instance1.colors.push('yello') // ['pink', 'blue', 'yello']
let instance2 = new SubType('ce')
instance2.say() // ce
instance2.colors // ['pink', 'blue']
- 优点:
1.可以向超类传递参数
2.解决原型中包含引用类型值被所有实例共享的问题
3.可以继承超类型定义的方法
- 缺点:
1.会调用两次超类型构造函数:一次是在创建子类型原型的时候,另一次是在子类型构造函数内部。
4.原型继承
–>是Object.create()的实现
function creatObj(o) {
function F(){}
F.prototype = o
return new F()
}
5.class继承
class Super{
constructor (name) {
this.name = name
}
sayName () {
return this.name
}
}
class SubType extends Super {
constructor (name, age) {
super(name)
this.age = age
}
sayHi () {
return super.sayName() + this.age + 'hi'
}
}
let ins1 = new SubType('qrq', '20)
ins1.sayHi() //qrq20hi