JavaScript and ES6, “global” variables

前端 未结 2 620
南笙
南笙 2020-12-23 10:09

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\'

相关标签:
2条回答
  • 2020-12-23 10:12

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

    0 讨论(0)
  • 2020-12-23 10:27

    What you are looking for is to create a singleton. From http://amanvirk.me/singleton-classes-in-es6/.

    let instance = null;
    export default class Cache{
      constructor() {
        if (!instance) { instance = this; }
        this.time = new Date()
    
        return instance;
      }
    }

    I tested this and it works. You would simply replace the this.time = new Date() with this.singletonFunction = function(){}. Where you want to use it do your import then

    let aSingleton = (new importName()).singletonFunction;

    0 讨论(0)
提交回复
热议问题