简体   繁体   English

使用Node.js从其他js文件引用构造函数

[英]Referencing a constructor from a different js file using Node.js

//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;
    }

}

I've also tried it with simply 我也尝试过

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

but that also returns "item.ItemTest is not a constructor". 但这还会返回“ item.ItemTest不是构造函数”。 if that function is added into default.js then it works just fine, but I don't know how to make it pull the constructor object from the other file. 如果将该函数添加到default.js中,那么它将正常工作,但是我不知道如何使其从另一个文件中提取构造函数对象。

I made few changes to your existing code by replacing these lines const item = require("./item.js"); 我通过替换这些行const item = require("./item.js");对您现有的代码进行了少量更改const item = require("./item.js"); and var itemTest = new item.ItemTest("weapon",1,1,1); var itemTest = new item.ItemTest("weapon",1,1,1); with these const ItemTest = require("./item"); 这些const ItemTest = require("./item"); and var itemTest = new ItemTest("weapon", 1, 1, 1); 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;

In the code above, I am exporting ItemTest so you have access to it when you use require() . 在上面的代码中,我正在导出ItemTest因此在使用require()时可以访问它。 On requiring the file, you get the class exported. 在需要文件时,您将导出类。

In Item.js you need to change 在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(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM