2017-04-20 45 views
0

我有一個文件。 a.js級聯需要在NodeJs中,需要一個需要另一個文件的文件NodeJs

class A{ 
    constructor(name){ 
     this.name = name; 
    } 

    displayName(){ 
    console.log(this.name); 
    } 
} 
module.exports = A; 

另一個文件 common.js

const A = require('./a'); 
exports.A; 

另一個文件b.js

const common = require('./common'); 
var a = new common.A('My name is khan and I am not a terrorist'); 
a.displayName(); 

我得到一個錯誤A是不是一個構造ctor。 請幫忙,怎樣才能完成。 請原諒我愚蠢的錯誤,我是新手。

+1

在a.js中你應該做的是:module.exports = A – WilomGfx

+0

並且在common.js中保持一致** module.exports = A ** – lomboboo

+0

對不起,它的module.exports =只有一個。讓我編輯問題。 – Imran

回答

3

這裏是修復,你應該......

a.js文件,要導出Render,但是,它應該是A,而不是...

class A { 
    constructor(name) { 
     this.name = name; 
    } 
    displayName() { 
     console.log(this.name); 
    } 
} 
module.exports = A; 

在你common.js文件,你要的是object的組成類common /函數/變量,或什麼的,導出如下所示:

const A = require('./a'); 
const someOtherVariable = 'Hello World!'; 
module.exports = { 
    A: A, 
    someOtherVariable: someOtherVariable, 
}; 

評論:你的原因「必須」是因爲你要使用的A類的語法如下:common.A ...假設該文件的名稱是common,你可能會export不僅僅是多了一個class,所以它們打包成一個object ...

最後,在b.js文件,然後你可以使用common.A語法來提取您正在尋找使用類...

const common = require('./common'); 
const a = new common.A('My name is khan'); 
a.displayName(); 
console.log(common.someOtherVariable); // Hello World! 

希望這有助於。