DamomHd / interview-question

整理各大厂面试题
1 stars 0 forks source link

JS如何实现继承? #12

Open DamomHd opened 3 years ago

DamomHd commented 3 years ago

通过call实现

function Parent1(){
    this.name = 'parent1'
}
function Child1(){
    Parent1.call(this)
    this.type = 'child1'
}
console.log(new Child1)
DamomHd commented 3 years ago

通过原型链

function Parent1(){
    this.info = [1,2,3]
    this.name = 'parent1'
}
function Child1(){
    this.type = 'child1'
}
Child1.prototype = new Parent1()

console.log(new Child1())
DamomHd commented 3 years ago

通过原型链和call

function Parent1(){
    this.info = [1,2,3]
    this.name = 'parent1'
}
function Child1(){
    Parent1.call(this)
    this.type = 'child1'
}
Child1.prototype = new Parent1()

console.log(new Child1())
DamomHd commented 3 years ago

组合继承优化1

function Parent1(){
    this.info = [1,2,3]
    this.name = 'parent1'
}
function Child1(){
    Parent1.call(this)
    this.type = 'child1'
}
Child1.prototype = Parent1.prototype
DamomHd commented 3 years ago

最佳推荐使用,寄生组合继承

function Parent1(){
    this.info = [1,2,3]
    this.name = 'parent1'
}
function Child1(){
    Parent1.call(this)
    this.type = 'child1'
}
Child1.prototype = Object.create(Parent1.prototype)
Child1.prototype.constructor = Child1
DamomHd commented 3 years ago

通过call实现

function Parent1(){
    this.name = 'parent1'
}
function Child1(){
    Parent1.call(this)
    this.type = 'child1'
}
console.log(new Child1)

问题:子类能够拿到父类属性值,父类原型对象一旦存在方法则子类无法继承

DamomHd commented 3 years ago

通过原型链

function Parent1(){
    this.info = [1,2,3]
    this.name = 'parent1'
}
function Child1(){
    this.type = 'child1'
}
Child1.prototype = new Parent1()

console.log(new Child1())

问题:两个实例使用同一个原型对象,改变属性多个实例也会改变

DamomHd commented 3 years ago

通过原型链和call

function Parent1(){
    this.info = [1,2,3]
    this.name = 'parent1'
}
function Child1(){
    Parent1.call(this)
    this.type = 'child1'
}
Child1.prototype = new Parent1()

console.log(new Child1())

问题:Parent1构造函数会多执行一次