user522170
user522170

Reputation: 651

How to import objects in Javascript/node

I have a file: main2.js

exports.obj = {

x : 10,
setX : function (y)
{
    this.x = y;
},
getX : function()
{
    return this.x;
}
};

Having two files: abc.js

  const obj = require("./main2").obj;
  describe("Test", function(){

  it("Set X", () => {
  obj.setX(50);

 })
})

def.js

  const obj = require("./main2").obj;
  describe("Test", function(){

  it("Get X", () => {
  console.log(obj.getX());

 })
})

When I ran both files together, I got 50 as the output, but I expected 10. I needed both files to have a different instance of obj. How do I achieve this?

Upvotes: 2

Views: 1184

Answers (3)

Renaud Reguieg
Renaud Reguieg

Reputation: 81

maybe another solution would be to unexpose x

filea.js

//Module.exports allow you to export the function without naming it

module.exports = () =>{// or module.exports = function(){
  let x=10;

function setX(i){
  x=i;
}

function getX(){
  return x;
}
  return {getX,setX}
}

fileb.js

const myPseudoClass= require('./fila');
const obj = myPseudoClass();
// can be replaced by const obj = require('./fila')();
console.log('x=',obj.getX());
obj.setX(50);
console.log('x=',obj.getX());

Upvotes: 0

Cristian Roman
Cristian Roman

Reputation: 26

When you use require you're getting a singlenton instance, so the second call is returning the same value as first. You have to export a factory function. Ex:

exports.generateObj = function(){
  return {
    x : 10,
    setX : function (y)
    {
        this.x = y;
    },
    getX : function()
    {
        return this.x;
    }
  }
};

And change the others .js with:

const obj = require("./main2").generateObj();

instead of:

const obj = require("./main2").obj;

Upvotes: 1

ZimGil
ZimGil

Reputation: 964

The problem is that you have a single object with couple of references to the same object. If you want to have a different object everytime, you may want to use a function or a class that will return this object.

Should look like this:

main2.js

exports.obj = function() {
  return {
    x : 10,
    setX : function (y) {
      this.x = y;
    },
    getX : function() {
      return this.x;
    }
  };
};

and then change other files to use const obj = require("./main2").obj()

Upvotes: 2

Related Questions