简体   繁体   中英

Easy accessible variable that isn't in the Global scope

I am building a game with the CreateJS library. In the current build I save a lot of my variables and objects in the Global scope, which is really neat and makes it easy for various extended classes to reuse SpriteSheets etc.

I am looking for a way to NOT use the global scope. Obviously I can pass the spritesheet, or a class which contains the spritesheet as a parameter to all displayobjects I make, but I was hoping there was a more clever way of doing this.

Any suggestions or tips on how to achieve this would be helpful.

You may want to use a module :

var main = (function(){
    var myPrivateVal1 = "Something";
    var myPrivateVal2 = 56;
    var myVeryPrivateVal = 3;

    //Return only what you want to expose
    return {
        myPublicVal: 123,
        getVal1: function(){
            return myPrivateVal1;   
        },
        getVal2: function(){
            return myPrivateVal2;   
        },
        doCalculation: function(){
            return myVeryPrivateVal * myPrivateVal2;
        }
    }
})();

console.log(main.myPublicVal); //123
console.log(main.myPrivateVal1); //undefined
console.log(main.myPrivateVal2); //undefined
console.log(main.myVeryPrivateVal); //undefined

console.log(main.getVal1()); //Something
console.log(main.getVal2()); //56
console.log(main.doCalculation()); //168

Here you have one global variable main , which is the module that exposes what you need to expose, but still keeps track of the variables needed.

See this JSFiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM