1

我有以下父类...

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

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

和相应的子类:

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

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

如何从 Parent 类继承,以便可以使用属性 id 和 name。

4

1 回答 1

3

我试图通过添加类似的东西来应用继承Child.prototype = Object.create(Parent.prototype);

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

如何从 Parent 类继承,以便可以使用属性 id 和 name。

您基本上需要对构造函数进行“超级”调用,以便它在实例Parent上设置您的属性:Child

function Child(id, name, parameters) {
  Parent.call(this, id, name, parameters);
  Object.defineProperty(this, "phone", {
    value: parameters.phone,
    writable: true
  });
}
于 2015-03-03T15:01:34.813 回答