baiomu
baiomu

Reputation: 113

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". 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.

Upvotes: 0

Views: 1105

Answers (2)

Tareq
Tareq

Reputation: 5363

In Item.js you need to change

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();

Upvotes: 0

codejockie
codejockie

Reputation: 10892

I made few changes to your existing code by replacing these lines const item = require("./item.js"); and var itemTest = new item.ItemTest("weapon",1,1,1); with these const ItemTest = require("./item"); and 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(). On requiring the file, you get the class exported.

Upvotes: 1

Related Questions