老师,你的组合继承优化2方式好像有点问题

来源:3-13 面向对象(二)

痞老板很帅

2019-07-14

是这样的,Parent和Child类的原型对象可能有函数,如果按照你这种组合继承的方式,好像子类Child的原型的函数就丢失了:

function Parent() {
    this.parentValue = 'parent'
    this.parentArray = [1, 2, 3]
}

Parent.prototype.sayYes = function () {
    console.warn('parent sayYes')
    console.log(this.parentValue, this.childValue)
}

function Child() {
    Parent.call(this)
    this.childValue = 'child'
}

Child.prototype.sayHello = function () {
    console.warn('child sayHello')
    console.log(this.parentValue, this.childValue)
}

Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child

var c = new Child()
console.log(c instanceof Child, c instanceof Parent)
console.log(c.constructor)

c.sayYes()
c.sayHello()

结果:
图片描述

你的组合继承的写法是这样的:

Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child

如果换成这样会不会好一点?

Child.prototype.__proto__ = Parent.prototype

运行结果好像是正确的:
图片描述

最后附上完整的测试代码,恳请老师帮忙看看最后这个写法有没有问题:

function Parent() {
    this.parentValue = 'parent'
    this.parentArray = [1, 2, 3]
}

Parent.prototype.sayYes = function () {
    console.warn('parent sayYes')
    console.log(this.parentValue, this.childValue)
}

function Child() {
    Parent.call(this)
    this.childValue = 'child'
}

Child.prototype.sayHello = function () {
    console.warn('child sayHello')
    console.log(this.parentValue, this.childValue)
}


console.warn('Child.prototype.__proto__ === Object.prototype')
console.log(Child.prototype.__proto__ === Object.prototype)
Child.prototype.__proto__ = Parent.prototype
var c1 = new Child()
var c2 = new Child()
console.warn('c1.constructor')
console.log(c1.constructor)
c1.sayHello()
c1.sayYes()
c1.parentArray.push(5)
console.warn('c1, c2')
console.log(c1, c2)
console.warn('c1.constructor === Child, c1.constructor === Parent')
console.log(c1.constructor === Child, c1.constructor === Parent)
console.warn('c1 instanceof Child, c1 instanceof Parent')
console.log(c1 instanceof Child, c1 instanceof Parent)

实验结果:
图片描述

写回答

1回答

快乐动起来呀

2019-07-16

同学你写的那个代码有问题,你先给child.prototype.sayYes赋值,然后用create来覆盖child.prototype那个sayYes自然就丢失了呀,create是返回一个新的对象

0
0

前端跳槽面试必备技巧 面试官全流程指导

一门让你能成功获取前端 Offer 的课程, 不只是技术,面试“技巧”也至关重要

4836 学习 · 830 问题

查看课程