[英]Easy accessible variable that isn't in the Global scope
I am building a game with the CreateJS library. 我正在使用CreateJS库构建游戏。 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.
在当前版本中,我将很多变量和对象保存在Global范围内,这确实很整洁,并且使各种扩展类都可以轻松重用SpriteSheets等。
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.
显然,我可以将spritesheet或包含spritesheet作为参数的类传递给我制作的所有displayobjects,但是我希望有一种更巧妙的方法来实现。
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. 在这里,您有一个全局变量main ,它是一个模块,它公开您需要公开的内容,但仍跟踪所需的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.