【问题标题】:javascript - prototype inheritance from generic to specific - better wayjavascript - 从通用到特定的原型继承 - 更好的方法
【发布时间】:2017-09-20 23:14:54
【问题描述】:

我正在尝试用更干净的方式来做到这一点:

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”原型继承“sound”属性,“Cat”从“Mammal”原型继承方法“purr”。但是我觉得那行

Cat.__proto__ = Mammal 

在某种程度上是错误的,不雅的,我不应该那样做嵌套继承。您能否确认并建议如何使其成为“好方法”?我想达到相同的结果,所以 purrer 继承了 Cat 和 Mammal 的数据

谢谢!

【问题讨论】:

  • 我读过的所有教程都说 setPrototypeOf 是性能杀手,所以应该改用 Object.create。

标签: javascript inheritance prototype


【解决方案1】:

你是对的,使用 '__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

【讨论】:

  • 不是所有的哺乳动物都会发出咕噜声。所以这是一个语义问题。也许将 purr() 更改为 emit_sound()
  • 这当然是解决问题的简单示例,在我的项目中没有这样的问题,也不是关于咕噜声:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-09
  • 2015-03-19
  • 1970-01-01
  • 2016-07-29
  • 2010-09-28
  • 1970-01-01
  • 2010-09-28
相关资源
最近更新 更多