chanjianyi
chanjianyi

Reputation: 615

where is the variable scope in es6 module?

I have 3 classes name A.js B.js and Util.js

Util.js:

just one static function for get the data and store it, then it dont need to make a request everytime.

import $ from 'jquery';
let store={};
class Util  {
    static storeGet(url,cb){
        //console.log(store);
        if(store[url]){
            cb(store[url])
        }else{
            $.get(url, (data) => {
                store[url]=data;
                cb(data);
            });
        }
    }   
}
export default Util;

my A and B is look like that

    ....
    import Util from './util';
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {stories: []};
      }

      componentDidMount() {
            Util.storeGet(Api.getList(), (result) => {
                const data = result;
                if (data) {
                   this.setState((prevState) => ({
                        stories: data.stories
                    }));
                }
            });
        }

      render() {
   ...

so now I can import this class from A or B,

and both A and B works fine and it seems share the store variable.

but we know A or B can't access store directly.

so I want to know where's the store variable scope actually?

why cant access store directly but by the function storeGet??

Upvotes: 1

Views: 1750

Answers (1)

Todd Chaffee
Todd Chaffee

Reputation: 6824

All variables declared inside an ES6 module are private to that module. Which is good. If you did want to make the store variable available to other code directly (probably not a good idea in this case), you change your code like this:

export let store = {};

And then use it like this:

import { store } from './util';

Upvotes: 3

Related Questions