从“抽象”基类“类”调用构造函数

我有以下要求:

  • 我的“超级”“类”必须是“抽象的”
  • 我的“超级”“类”的构造函数必须由inheritance类调用
  • inheritance的“类”的构造函数必须做一些东西…

我这样试了:

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); 确保我的超类的构造函数被调用。 但是那this.constructor === Father是真的。

有没有更好的办法?

问题是你没有正确设置constructor属性时进行派生。 在这行之后:

 Son.prototype = Object.create(Father.prototype); 

你需要

 Son.prototype.constructor = Son; 

这只是用构造函数做这种inheritance的样板的一部分。 没有它, Son.prototypeinheritance了Father.prototype.constructor属性,它是由JavaScript引擎在创buildFather函数时设置的。 你必须明确地为Son做,因为你要replace Son.prototype上的对象(这是正确的事情,你只需要做这个constructor fixup)。