Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

reactjs - JavaScript and ES6, "global" variables

I've been working with little snippets of JavaScript during 3 years, but now I'm building a React application and I'm getting into it. There is a basic thing that I don't understand. React uses a Dispatcher and Stores to build its Flux pattern, the thing that I don't get is that this Dispatcher is visible in all the application, because Actions use the dispatcher to dispatch actions and Stores register to the Dispatcher to get notified (so it's not a new Dispatcher every time). So, how can I achieve this "global" scope or whatever it is called? How can achieve this using ES6 classes (modules)?

This question may be unclear due to my lack of experience programming real JavaScript, I hope that with the hep of community comments I'll be able to arrange that.

question from:https://stackoverflow.com/questions/33875322/javascript-and-es6-global-variables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can always assign variables to window.MyClass = whatever (global.MyClass for nodejs) no matter where you are, and access these values from any other file in your application. That's not always the best way to go about sharing data globally in your application though. The module loader in nodejs (or AMD in ES6) takes whatever you export and caches it. Lets say you have a file like:

MyModule.js:

class MyClass {
  constructor() {
    this.someData = 55;
  }
}

export default (new MyClass);

now whenever we require this file from elsewhere, we're ALWAYS being given the SAME instance of MyClass. This means:

file1.js:

import MyClass from './MyModule'
MyClass.someData = 100;

file2.js:

import MyClass from './MyModule'
console.log(MyClass.someData);

This is called the singleton pattern, where we pass around one common instance of your class all throughout your application. So in this manner we're able to access the same instance of MyClass from different files, all without polluting the global scope (we avoid making assignments to global.MyClass but accomplish the same functionality).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...