0

I've a bigger object where I save all important data of my main class. My project is getting kinda bigger so I've some seperated files/classes. All of them need to have access to my store object, which values gonna change from time to time.

I know I could just export/import my store to each class, but then the changes are kinda super global, what means if I instantiate my main class more than once and I change the store in the first instantiated main class, then the second instantiated main class would see the changes of my store too. Hope I could explain well enough.

Here is an very simple example with just 2 classes, but I've far more:

index.js

let ClassA = require('./ClassA')
let ClassB = require('./ClassB')

let store = {
    propA: 1,
    propB: 2
}

class mainClass {
    constructor() {
        console.log('main Class')
        this.doSomething()
    }

    doSomething() {
        let classA = new ClassA() // get/edit store there
        let classB = new ClassB() // get/edit store there

        classA.doSomething()
        classB.doSomething()
    }
}

let instantiatePorject = new mainClass()

ClassA.js

module.exports = class ClassA {
    doSomething() {
        // get/edit store here
    }
}

ClassB.js

module.exports = class ClassB {
    doSomething() {
        // get/edit store here
    }
}
bonblow
  • 1,151
  • 6
  • 19
  • 28

1 Answers1

0

Pass in your store when constructing your objects

let ClassA = require('./ClassA')
let ClassB = require('./ClassB')

let store = {
    propA: 1,
    propB: 2
}

class mainClass {
    constructor() {
        console.log('main Class')
        this.doSomething()
    }

    doSomething() {
        let classA = new ClassA(store) // get/edit store there
        let classB = new ClassB(store) // get/edit store there

        classA.doSomething()
        classB.doSomething()
    }
}

let instantiatePorject = new mainClass()
rtn
  • 127,556
  • 20
  • 111
  • 121
  • Ty, that's what I don't wanna do, cause my project is kinda large. A lot of classes, a lot of functions inside this classes. Of couse I know this solution but I hope there is something cleaner. – bonblow Mar 09 '18 at 23:52
  • Yes, it should be global for other files/classes. – bonblow Mar 09 '18 at 23:56
  • So you have to pass that information in some way. Either pass the object into the constructor, or through some other function, or have the class files require the store in. – rtn Mar 09 '18 at 23:58