I have a javascript function the initializes a bunch of global varaibles for a game.
function buildVariables(fs,fm) {
window.p1HPStart = fm.p1hp;
window.p2HPStart = fm.p2hp;
window.p1HP = 100;
window.p2HP = 100;
window.trn = 0;
}
Right now all this javascript is in the same HTML file. I want to move it to its own .js file and include it in this HTML file. I also want to replace “window” with a different global namespace like fight.p1HP.
How can I do this?
I’ve seen code like the below as a proposed answer in other similar questions, but I don’t quite understand how it can be used to replace window.
var cartTotaler = (function () {
var total = 0; tax = 0.05;
// other code
return {
addItem : function (item) { },
removeItem : function (item) { },
calculateTitle : function () { }
};
}());
Thanks.
Then just make sure everywhere you want one of your own variables, you use your namespace in front of it:
Note: this doesn’t really “replace” the
windowobject (as there is no way to do that) – it just puts all your global variables into one master global object rather than pollute the global namespace with every single one of your variables.The name
mySpacecan be anything you want it to be. Typically, it should be something that is unique to your application that is unlikely to conflict with something any other javascript or library might use.