简体   繁体   English

节点js的奇怪错误:TypeError X不是构造函数

[英]Weird error with node js: TypeError X not a constructor

Anyone know why this is happening?有谁知道为什么会这样?

I have a pretty complex system so to simplify it we have this code:我有一个非常复杂的系统,所以为了简化它,我们有以下代码:

profile_manager.js 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 profile.js

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

module.exports = Profile;

index.js index.js

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

Once.doThing() is called, I get a TypeError saying that "Profile is not a constructor".一旦.doThing() 被调用,我得到一个 TypeError 说“Profile 不是构造函数”。

HOWEVER... When I change profile_manager.js to the following code below, it works perfectly.但是...当我将 profile_manager.js 更改为以下代码时,它可以完美运行。 No TypeError.没有类型错误。

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

I even console.logged the prf object and it works the way I want it to.我什至 console.logged prf object 并且它按照我想要的方式工作。 Why does it only work when I move the "const Profile = require('./profile');"为什么它只在我移动“const Profile = require('./profile');”时才起作用within the method but when I put it at the top of the module, it does not want to work.在方法中,但是当我把它放在模块的顶部时,它不想工作。

I found out that profile.js had an instance of profile_manager.js or something like that我发现 profile.js 有一个 profile_manager.js 的实例或类似的东西

This post talks more about it How to deal with cyclic dependencies in Node.js这篇文章详细讨论了如何处理 Node.js 中的循环依赖

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM