【问题标题】:Weird error with node js: TypeError X not a constructor节点js的奇怪错误:TypeError X不是构造函数
【发布时间】:2020-11-24 01:54:09
【问题描述】:

有人知道为什么会这样吗?

我有一个非常复杂的系统,所以为了简化它,我们有以下代码:

profile_manager.js

const Profile = require('./profile');

class ProfileManager {
  doThing() {
    const prf = new Profile("Lemon", "ade");
  }
}
const prfManager = new ProfileManager();
module.exports = prfManager;

profile.js

class Profile {
  constructor(arg0, arg1) {
    //do thing
  }
}

module.exports = Profile;

index.js

const prfManager = require('./profile_manager');
prfManager.doThing();

一旦 .doThing() 被调用,我得到一个 TypeError 说“Profile is not a constructor”。

但是...当我将 profile_manager.js 更改为以下代码时,它可以完美运行。没有类型错误。

class ProfileManager {
  doThing() {
    const Profile = require('./profile');
    const prf = new Profile("Lemon", "ade");
  }
}
const prfManager = new ProfileManager();
module.exports = prfManager;

我什至 console.logged prf 对象,它按我想要的方式工作。为什么它只在我移动“const Profile = require('./profile');”时才起作用在方法中,但是当我把它放在模块的顶部时,它不想工作。

【问题讨论】:

  • 无法重现,节点 v12.10.0。有谁赞成关心来启发我?
  • 是的,到目前为止,我已将您的代码复制粘贴到 NodeJs v 10 中,并且运行良好。现在我将尝试使用 Node v 12

标签: javascript node.js constructor typeerror node-modules


【解决方案1】:

我发现 profile.js 有一个 profile_manager.js 的实例或类似的东西

这篇文章更多地谈论它How to deal with cyclic dependencies in Node.js

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 1970-01-01
    • 2021-09-28
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 2017-09-29
    相关资源
    最近更新 更多