How to keep the state of the javascript object imported with ES6?

advertisements

I'd like to initialise an object with specific values, and have another object that uses the value of the previously initialized object... Better than too many words, I have the following:

// file1.js
export default {
  myVar1: null,
  initialize(value) {
    this.myVar1 = value
  }
}

The file2 imports file1 and create a function to print myVar1

// file2.js
import { myVar1 } from 'file1'

export default {
  printVar() {
    console.log(myVar1)
  }
}

file3 initialize file1 and uses file2 to print the value of myVar1

// file3.js
import File1 from 'file1'
import File2 from 'file2'

File1.initialize('hello world')
File2.printVar() // logs undefined

I want to initialize file1 and wants file2 to access the value of file1 to print it. Although its value is undefined when it gets imported.

I would like to use a factory pattern in Javascript to do that. Is there a way to achieve the following?

Thanks


Change your file2 to this

import file1 from './file1'

export default {
  printVar() {
    console.log(file1.myVar1)
  }
}