【发布时间】:2019-04-19 14:28:36
【问题描述】:
在 JavaScript 中,当分配新类的原型时没有适合使用的构造函数时,如何扩展基类?解决方案...
- 必须通过
instanceof测试。 - 不得修改现有构造函数。
- 必须调用超级构造函数。
- 不得包含我编写的中间类。
- 不得依赖第三方代码,如 jQuery。
- 可能涉及您提供的帮助函数。
这是我尝试过的。
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.
我的解决方案失败了,因为抛出了异常
【问题讨论】:
-
getName现在有缺陷 -
你有没有考虑过使用 es6
class: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…?
标签: javascript inheritance constructor