Javascript 继承用 Object.defineProperty 定义的属性

Javascript inheritance of properties defined with Object.defineProperty

我有以下 parent class...

function Parent(id, name, parameters) {
  Object.defineProperty(this, "id", {
    value: id
  });

  Object.defineProperty(this, "name", {
    value: name,
    writable: true
  });
};

和对应的child class:

function Child(id, name, parameters) {
  Object.defineProperty(this, "phone", {
    value: parameters.phone,
    writable: true
  });
};

我试图通过添加类似的东西来应用继承 Child.prototype = Object.create(Parent.prototype); ,但这显然行不通。

如何从 Parent class 继承,以便我可以使用属性 id 和名称。

I tried to apply inheritance by adding something like Child.prototype = Object.create(Parent.prototype);

是的,您应该这样做,以在 .prototype 对象之间创建原型链。你已经在它们上面定义了你的方法,不是吗?

How can I inherit from the Parent class such that I can use the properties id and name.

您基本上需要 "super" 调用 Parent 构造函数,以便它在 Child 个实例上设置您的属性:

function Child(id, name, parameters) {
  Parent.call(this, id, name, parameters);
  Object.defineProperty(this, "phone", {
    value: parameters.phone,
    writable: true
  });
}