javascript - 从泛型到特定的原型继承 - 更好的方法

时间:2017-09-20 23:14:55

标签: javascript inheritance prototype

我正在尝试更清晰地做到这一点:

let Mammal = {
    purr: function () {
        console.log("it's sound is:", this.sound)
    }
}

let Cat = {
    sound: "meow"
}

Cat.__proto__ = Mammal;
let purrer = Object.create(Cat)
purrer.purr(); // it's sound is: meow

现在代码按预期工作。对象“purrer”从“Cat”原型继承“声音”属性,“Cat”从“哺乳动物”原型继承方法“purr”。但是我觉得那条线

Cat.__proto__ = Mammal 

在某种程度上是错误的,不优雅的,我不应该以这种方式进行嵌套继承。能否请您确认并建议如何使其成为“好方法”?我希望获得相同的结果,因此purrer继承了Cat和Mammal的数据

谢谢!

1 个答案:

答案 0 :(得分:2)

你正确使用' __ proto ____'是一个可怕的问题,你不应该改变已经创建的对象原型,它在语义上是错误的,它可能会导致性能问题。 你为什么遇到这个问题?答案很简单`你的oop建模是错误的。 这就是你应该做的事情

class Mammal {
    constructor() {
        this.sound = "Mammal sound";
    }
    purr() {
        console.log("it's sound is:", this.sound)
    }
}

class Cat extends Mammal {
    constructor() {
        super();
        this.sound = "meow"
    }
}

let purrer = new Cat();
purrer.purr(); // This also will meow