节点 js 的奇怪错误:TypeError X 不是构造函数
Weird error with node js: TypeError X not a constructor
有人知道为什么会这样吗?
我有一个非常复杂的系统,所以为了简化它,我们有以下代码:
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 不是构造函数”。
但是...当我将 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');”时它才起作用在方法中但是当我把它放在模块的顶部时,它不想工作。
我发现 profile.js 有一个 profile_manager.js 或类似的实例
这 post 讨论更多 How to deal with cyclic dependencies in Node.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
class Profile {
constructor(arg0, arg1) {
//do thing
}
}
module.exports = Profile;
index.js
const prfManager = require('./profile_manager');
prfManager.doThing();
调用 .doThing() 后,我收到一个 TypeError,提示“Profile 不是构造函数”。
但是...当我将 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');”时它才起作用在方法中但是当我把它放在模块的顶部时,它不想工作。
我发现 profile.js 有一个 profile_manager.js 或类似的实例
这 post 讨论更多 How to deal with cyclic dependencies in Node.js