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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…