原型继承
- 说明:将子类的原型设置为父类实例
- 缺点:
- 子类new出来的实例,父类的属性没有隔离,会相互影响,引用同一地址;
- 子类不能向父类传参数
function Parent() {
this.name = 'parent'
}
Parent.prototype.getName = function() {
console.log(this.name)
}
function Child() {
this.name = 'child'
}
Child.prototype = new Parent() // 原型继承核心代码
let child = new Child()
构造函数继承
- 说明:使用call()方法继承,子类继承父类的属性和方法, 子类能向父类传参数
- 缺点:不能继承父类的原型属性和原型方法
function Parent() {
this.name = 'parent'
}
Parent.prototype.getName = function() {
console.log(this.name)
}
function Child() {
Parent.call(this)
this.name = 'child'
}
let child = new Child()
组合式继承
- 组合上面的构造函数与原型继承的功能;
- 缺点:call()方法已经拿到父类所有的属性 ,后面再使用原型时也会有父类所有属性;没有解决引用同一地址问题
function Parent() {
this.name = 'Parent'
}
Parent.prototype.getName = function() {
console.log(this.name)
}
function Child(value) {
Parent.call(this) // 构造函数继承
this.name = 'Child'
}
Child.prototype = new Parent() // 原型继承
let child = new Child()
寄生组合继承
- 使用借用构造函数(call)来继承父类this声明的属性/方法
- 设置子类prototype原型为父类prototype,来继承父类的prototype声明的属性/方法
- (注意) 子类原型的constructor指向子类
function Parent() {
this.name = 'parent'
}
Parent.prototype.getName = function() {
console.log(this.name)
}
function Child() {
Parent.call(this)
this.name = 'child
}
Child.prototype = Parent.prototype
// Child.prototype = Object.create(Parent.prototype)
Child.prototype.contructor = Child
let child = new Child()
es6 类继承
class Parent {
contructor() {
this.name = 'parent'
}
getName() {
console.log(this.name)
}
}
class Child extends Parent {
contrucotr() {
super()
this.name = 'child'
}
}
let child = new Child()