简体   繁体   English

如何使用ES6保持javascript导入对象的状态?

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

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导入file1并创建一个函数来打印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初始化file1并使用file2打印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. 我想初始化file1,并希望file2访问file1的值以进行打印。 Although its value is undefined when it gets imported. 尽管在导入时未定义其值。

I would like to use a factory pattern in Javascript to do that. 我想在Javascript中使用工厂模式来做到这一点。 Is there a way to achieve the following? 有没有办法实现以下目标?

Thanks 谢谢

Change your file2 to this 将您的file2更改为此

import file1 from './file1'

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

This is an anti-pattern to depend on the module caching and object references for such issues, regardless. 无论如何,这都是一种依赖于模块缓存和对象引用的反模式。

you need to import the whole file to get the reference instead of the actual value, so you have to do: 您需要导入整个文件以获取引用而不是实际值,因此您必须执行以下操作:

import file1 from './file1'

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

this way u dont just import the value of myVar1 , you import a reference to the object, so you can modify the object content and always get it reflected everywhere. 这样,您不只是导入myVar1的值,而是导入对对象的引用,因此您可以修改对象的内容并始终将其反映在任何地方。

PS this is NOT recommended, and NOT good composition. PS这是不推荐的,也不是很好的组成。

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

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