Nodejs上的Javascript ES6:TypeError:object不是构造函数
我有这个样本类sync.js作为我的项目上的某个模块。
'use strict'; export default class Sync{ constructor(dbConnection){ this.dbConnection = dbConnection; } test(){ return "This is a test " + this.dbConnection; } }
然后在我的控制器上的某个地方,我使用这个类:
'use strict'; import Sync from '../../path/to/module'; // <-- works fine const sync = new Sync('CONNECTION!'); // <-- meh console.log(sync.test());
我期待这样的事情被logging在控制台上This is a test CONNECTION!
。 但是,我得到这个错误。 TypeError: object is not a constructor
我做错了什么?
顺便说一句,如果我删除了行const sync = new Sync('CONNECTION!');
并将console.log()
更改为console.log(Sync.test());
输出This is a test undefined
打印这是我所期望的。 但是我的安装有什么问题?
WTF?
编辑
伙计们,我想我发现了这个问题,根据@JLRishe和rem035指出,它是返回类的实例,而不是类本身。 事实上,有一个index.js
导入'./sync'
文件并导出为export default new Sync();
。 这里是整个index.js
。
'use strict'; import Sync from './sync'; export default new Sync(); // <-- potential prodigal code
模块树看起来像这样。
module | |_ lib | |_ index.js // this is the index.js I am talking about | |_ sync.js | |_ index.js // the entry point, contains just `module.exports = require('./lib');`
现在。 如何导出export default new Sync();
没有做new
?
编辑2
如何导出导出默认的新同步(); 没有做新的?
只要从module/lib/index.js
删除new
关键字:
import Sync from './sync'; export default Sync;
或者直接从module/lib/sync.js
编辑1
根据你所说的logging,
Sync { dbConnection: undefined }
看起来像你的import正在返回类的一个实例(这是一个对象),而不是类定义本身。
所以console.log(new Sync())
将返回你在说什么,
class Sync { constructor(dbConnection) { this.dbConnection = dbConnection; } test() { return "This is a test " + this.dbConnection; } } console.log(new Sync());
由于这是谷歌最重要的结果:
如果在Node中使用require()
语句来导入类并引入循环依赖,则会突然看到此错误popup,因为require()
返回的是类而不是类。