我有这个样本班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());
我期待在控制台上记录类似的内容This is a test CONNECTION!
。但我却收到了这个错误。TypeError: object is not a constructor
我做错了什么?
顺便说一句,如果我删除了这条线const sync = new Sync('CONNECTION!');
并改变了console.log()
to console.log(Sync.test());
输出This is a test undefined
打印出来的内容正是我所期望的。但是我的实例化有什么问题吗?
WTF?
Edit
伙计们,我想我发现了问题,基于@JLRishe and rem035指出,它返回的是类的实例而不是类本身。事实上有一个index.js
进口的'./sync'
js 文件并导出为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
?