使用Node.js从不同的js文件引用构造函数

时间:2017-12-25 20:49:52

标签: javascript node.js require

//default.js
const item = require("./item.js");
var itemTest = new item.ItemTest("weapon",1,1,1);
console.log(itemTest.name);

//item.js

module.exports = class ItemTest {
    constructor(name, value, attack, defense) {
        this.name = name;
        this.value = value;
        this.attack = attack;
        this.defense = defense;
    }

}

我也只是用

尝试过
 //item.js
    function ItemTest(name, value, attack, defense) {
        this.name = name;
        this.value = value;
        this.attack = attack;
        this.defense = defense;
    }

但是也返回“item.ItemTest不是构造函数”。如果该函数被添加到default.js然后它工作正常,但我不知道如何使其从另一个文件中拉出构造函数对象。

2 个答案:

答案 0 :(得分:1)

我使用这些const item = require("./item.js");var itemTest = new item.ItemTest("weapon",1,1,1);

替换这些行const ItemTest = require("./item");var itemTest = new ItemTest("weapon", 1, 1, 1);,对现有代码进行了一些更改
//default.js
const ItemTest = require("./item");
var itemTest = new ItemTest("weapon", 1, 1, 1);
console.log(itemTest.name);

//item.js
class ItemTest {
    constructor(name, value, attack, defense) {
        this.name = name;
        this.value = value;
        this.attack = attack;
        this.defense = defense;
    }

}

module.exports = ItemTest;

在上面的代码中,我正在导出ItemTest,因此您在使用require()时可以访问它。在需要该文件时,您将获得导出的类。

答案 1 :(得分:0)

在Item.js中你需要改变

class ItemTest {
    constructor(name, value, attack, defense) {
        this.name = name;
        this.value = value;
        this.attack = attack;
        this.defense = defense;
    }

}

class MyClass {}

// If you want to export more stuff, do
module.exports = {ItemTest: ItemTest, MyClass: MyClass};


// But if you have only ItemTest, then you can do
module.exports = ItemTest;

// This will change the main code to be like 
var ItemTest = require('./item');
var itemTest = new ItemTest();