javascript - 从 "abstract"基址 "class"调用构造函数

标签 javascript node.js

我有以下要求:

  • 我的“ 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/

相关文章:

javascript - forEach 中的异步等待

javascript - 如何以 Angular 修复 ng build 项目

javascript - 在窗口调整大小时调用移动菜单功能

javascript - JS时刻时区

javascript - JWPlayer 控制栏导致回传

javascript - 每个函数都应该是一个闭包吗?

javascript - 为 Node 微服务编写重试逻辑的最佳方法是什么?

javascript - JS/jQuery 根据单选/选择值显示文本框

javascript - 是否可以使用 Javascript 在页面刷新时随机生成预先确定的链接颜色和悬停颜色?

javascript - 在 Iron Router 中使用布局时向 <head> 添加行