【问题标题】:How to extend a class in JavaScript, when it has no default constructor?没有默认构造函数时,如何在 JavaScript 中扩展一个类?
【发布时间】:2019-04-19 14:28:36
【问题描述】:

在 JavaScript 中,当分配新类的原型时没有适合使用的构造函数时,如何扩展基类?解决方案...

  1. 必须通过instanceof 测试。
  2. 不得修改现有构造函数。
  3. 必须调用超级构造函数。
  4. 不得包含我编写的中间类。
  5. 不得依赖第三方代码,如 jQuery。
  6. 可能涉及您提供的帮助函数。

这是我尝试过的。

function Person(name) { // Immutable base class.
  if (typeof name != "string" || name == "") {
    throw new Error("A person must have a valid name.");
  }
  this.getName = function() {
    return name;
  }
}

function Artist(name) { // My extending class.
  Person.call(this, name); // Call super constructor.
}
Artist.prototype = new Person(); // Express inheritance without parameters.
var tom = new Artist("Tom");
console.info(tom instanceof Person); // Must print true.
console.info(tom.getName()); // Must print Tom.

我的解决方案失败了,因为抛出了异常

【问题讨论】:

标签: javascript inheritance constructor


【解决方案1】:

你做的继承错了,应该是:

Artist.prototype = Object.create(Person.prototype);

这行得通,你的所有测试都通过了。

有用的阅读:Inheritance in JavaScript

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-05
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    相关资源
    最近更新 更多