在 JavaScript 中,当分配新类的原型(prototype)时没有适合使用的构造函数时,如何扩展基类?解决方案...
- 必须通过
instanceof
测试。 - 不得修改现有构造函数。
- 必须调用 super 构造函数。
- 不得包含我编写的中间类。
- 不得依赖第三方代码,例如 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.
我的解决方案失败,因为抛出异常
最佳答案
你做的继承是错误的,应该是:
Artist.prototype = Object.create(Person.prototype);
这有效,并且您的所有测试都已通过。
关于javascript - 当 JavaScript 中的类没有默认构造函数时,如何扩展它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55763403/