Object.create()添加constructor属性

来源:5-11 【TS继承准备】寄生组合继承实现方式【最佳继承模式】-3

慕圣2122384

2022-03-25

老师,我在Object.create()添加constructor属性,是不是也可以,我测试了一下结果也是正确的。

function People(name, sex, phone) {
this.name = name
this.sex = sex
this.phone = phone
}

People.prototype.doEat = function () {
console.log(this.name + ’ 吃饭’)
}

function ChinesePeople(name, sex, phone, national) {
People.call(this, name, sex, phone)
this.national = national
}

let middle = Object.create(People.prototype, {
count: {
writable: true,
value: 23
},
constructor: {
value: ChinesePeople
}
})
ChinesePeople.prototype = middle
// ChinesePeople.prototype.constructor = ChinesePeople

let chinesePeopleOne = new ChinesePeople(‘lisi’, ‘男’, ‘132323232’, ‘汉’)
console.log(chinesePeopleOne)

图片描述

写回答

1回答

keviny79

2022-03-26

是的 正确,老师在视频说丢了一句话,谢谢同学!

 还要补充一句的是:TS继承底层没有用Object.create 用的是老师讲的手写中间对象的方式来实现的,TS考虑手写的源码优化中的方式来封装,能更灵活增加代码。




0
0

晋级TypeScript高手,成为抢手的前端开发人才

轻松驾驭 TypeScript 高级用法, 突破前端成长瓶颈

871 学习 · 425 问题

查看课程