【发布时间】:2016-07-27 18:20:25
【问题描述】:
我有这个示例类 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() 更改为console.log(Sync.test());,则会打印输出This is a test undefined,这与我的预期相符。但是我的实例化有什么问题?
WTF?
编辑
伙计们,我想我发现了问题,基于@JLRishe 和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');`
现在。如何在不执行new 的情况下导出export default new Sync();?
【问题讨论】:
-
这对我来说很好
-
WTH?真的吗? @nem035 这很奇怪。 :(
-
您确定没有在默认导出中意外添加
new吗?您向我们展示的代码确实导出了类,而不是实例。 -
@TheGreenFoxx 看起来很清楚你的
Sync变量是Sync类的instance,而不是类本身。虽然说不出为什么。您是否向我们展示了您的 sync.js 文件的完整内容(未修改)? -
@TheGreenFoxx 但它是整个模块代码吗?你确定你没有在里面的某个地方做
Sync = new Sync吗?
标签: javascript node.js ecmascript-6