[英]Javascript ES6 on Nodejs : TypeError: object is not a constructor
我有這個示例類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
,這正是我所期望的。 但是我的安裝有什么問題?
跆拳道?
編輯
伙計們,我想我發現了問題,基於@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');`
現在。 我如何導出export default new Sync();
不做new
?
編輯 2
我如何導出導出默認的新同步(); 不做新的?
只需從module/lib/index.js
刪除new
關鍵字:
import Sync from './sync';
export default Sync;
或者直接從module/lib/sync.js
編輯 1
根據你所說的記錄,
Sync { dbConnection: undefined }
似乎您的導入正在返回類的實例(它是一個對象),而不是類定義本身。
所以console.log(new Sync())
會返回你所說的,
class Sync { constructor(dbConnection) { this.dbConnection = dbConnection; } test() { return "This is a test " + this.dbConnection; } } console.log(new Sync());
不是console.log(Sync)
class Sync { constructor(dbConnection) { this.dbConnection = dbConnection; } test() { return "This is a test " + this.dbConnection; } } console.log(Sync);
您確定在導出之前沒有在任何地方調用new Sync
嗎?
初步答復
有問題的代碼工作正常:
'use strict'; class Sync { constructor(dbConnection) { this.dbConnection = dbConnection; } test() { return "This is a test " + this.dbConnection; } } const sync = new Sync('CONNECTION!'); console.log(sync.test());
根據您的錯誤:
TypeError: object is not a constructor
您的import
不回你怎么想它的返回和你正在嘗試new
東西,不能被實例化。
很可能您的import
路徑是錯誤的。
由於這是谷歌上的最佳結果:
如果你在 Node 中使用require()
語句導入類並引入循環依賴,你會突然看到這個錯誤彈出,因為require()
返回的是{}
而不是類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.