首页 > 解决方案 > 奇怪的继承问题“没有'new'就不能调用”

问题描述

以为我昨天已经解决了这个问题,但我显然没有,在又一整天试图解决这个问题之后,我再次寻求帮助。

我有一个npm link用 ES6 编写的“安装”模块。我正在导出一个名为 Perishable 的类。如果问题仍然存在,我已将课程精简到最低限度。

export default class Perishable {
    constructor() {

    }
}

我正在尝试扩展课程,我这样做是这样的:

// Perishable is imported already and IS NOT NULL. 
export default class Apple extends Perishable {
    constructor() {
        super()
    }
}

调用时new Apple()出现以下错误: Class constructor Perishable cannot be invoked without 'new'

但是,我可以直接通过创建一个新的 Perishable 类new Perishable()而没有任何问题。


要添加到这一点,将类复制+粘贴到同一目录中并使用相对路径导入它可以让我正确调用new Apple(). 我相信这与 webpack/babel 转换符号链接类的方式有关。这是我在检查转译代码时得到的:符号链接类

var Apple = function (_Perishable) {
    _inherits(Apple,  _Perishable);

    function Apple() {
        _classCallCheck(this, Apple);

        return _possibleConstructorReturn(this, (Apple.__proto__ || Object.getPrototypeOf(Apple)).call(this));
    }

    return Apple;
}(_idleEngine.Perishable);

这是我检查本地类的代码时得到的(正常工作)。

var Apple = function (_Perishable) {
    _inherits(Apple, _Perishable);

    function Apple() {
        _classCallCheck(this, Apple);

        return _possibleConstructorReturn(this, (Apple.__proto__ || Object.getPrototypeOf(Apple)).call(this));
    }

    return Apple;
}(_Perishable3.default);

两个生成的代码之间的唯一区别是最后的卷曲是什么,一个是(_idleEngine.Perishable),一个是(_Perishable3.default)

console.log(Perishable)对两种类型的导入返回相同的东西,并且new Perishable()对两种导入都有效。


我应该补充一点,符号链接的类是通过 a 导入的npm link,而local我刚刚从库中复制+粘贴的类与 Apple 类位于同一文件夹中。


编辑:这似乎只是系统链接模块的问题,因为发布模块“修复”了问题。

标签: javascriptwebpackecmascript-6babeljs

解决方案


推荐阅读