我有以下要求:
- 我的“ super ”“类”必须是“抽象”
- 我的“ super ”“类”的构造函数必须由继承的类调用
- 继承的“类”的构造函数必须做一些事情......
我试过这样:
var Father = function() {
if(this.constructor === Father) {
// ...I throw an exception here to make it "abstract"...
}
alert('Father constructor');
};
Father.prototype.say = function() {
alert('Im your father');
};
var Son = function() {
Father.call(this);
alert('Son constructor');
};
Son.prototype = Object.create(Father.prototype);
var son = new Son();
son.say();
使用 this.constructor === Father
我尝试将 Father
实现为“抽象”“类”(如果这是真的,我会在我的真实代码)。
Father.call(this);
确保调用我的父类(super class)的构造函数。但是 this.constructor === Father
为 true。
还有更好的办法吗?
最佳答案
问题在于您在进行派生时没有正确设置constructor
属性。此行之后:
Son.prototype = Object.create(Father.prototype);
你需要
Son.prototype.constructor = Son;
这只是使用构造函数进行此类继承的样板文件的一部分。如果没有它,Son.prototype
就会继承 Father.prototype.constructor
属性,该属性是由 JavaScript 引擎在创建 Father
函数时设置的。您必须为 Son
明确执行此操作,因为您要替换 Son.prototype
上的对象(这是正确的做法,您只需要执行此构造函数
修复即可)。
关于javascript - 从 "abstract"基址 "class"调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28410158/