缺点: 多个实例使用同一个原型对象
function Parent2() { this.name = 'parent2' this.play = [1, 2, 3] } function Child2() { this.type = 'child2' } Child2.prototype = new Parent2() const c2 = new Child2() console.log(c2) // { type: "child2" } console.log(c2.name) // parent2 console.log(c2.play) // [1, 2, 3]
看似没有问题,父类的方法和属性都能够访问,但实际上有一个潜在的不足。举个例子:
因为两个实例使用的是同一个原型对象, 所以改变c21的play属性,c22的play属性也跟着变了
const c21 = new Child2() const c22 = new Child2() c21.play.push(4) console.log(c22.play) // [1, 2, 3, 4] console.log(c21.play === c22.play) // true