//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然后它工作正常,但我不知道如何使其从另一个文件中拉出构造函数对象。
答案 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();