JavaScript和ES6,“全局”变量 [英] JavaScript and ES6, "global" variables

查看:87
本文介绍了JavaScript和ES6,“全局”变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在3年内一直在使用JavaScript的小片段,但现在我正在构建一个React应用程序,我正在进入它。有一件事我不明白。 React使用Dispatcher和Stores来构建其Flux模式,我没有得到的是这个Dispatcher在所有应用程序中都可见,因为Actions使用调度程序来调度操作,并且Stores注册到Dispatcher以获得通知(所以它不是每次新的Dispatcher)。那么,我怎样才能实现这个全球范围或其他任何范围呢?如何使用ES6类(模块)实现这一目标?

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)?

由于我缺乏编写真实JavaScript的经验,这个问题可能不清楚,我希望用社区评论来解决这个问题我将能够安排。

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.

推荐答案

您始终可以将变量分配给 window.MyClass =无论你在哪里 global.MyClass ,无论你在哪里),并从你的应用程序中的任何其他文件中访问这些值。然而,这并不总是在您的应用程序中全局共享数据的最佳方式。 nodejs(或ES6中的AMD)中的模块加载器接受您导出的任何内容并对其进行缓存。假设您有一个类似的文件:

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:

MyModule.js:

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

export default (new MyClass);

现在每当我们从其他地方需要这个文件时,我们总是被给予<$ $的SAME实例C $ C> 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);

这称为单例模式,我们在整个应用程序中传递您的类的一个公共实例。因此,通过这种方式,我们可以从不同的文件访问同一个 MyClass 的实例,所有这些都不会污染全局范围(我们避免分配给 global.MyClass 但完成相同的功能。)

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).

这篇关于JavaScript和ES6,“全局”变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆