Dave Chenell
Dave Chenell

Reputation: 601

Replacing window with custom javascript global namespace

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.

Upvotes: 0

Views: 714

Answers (2)

jackwanders
jackwanders

Reputation: 16050

(function(global){
     global.p1HPStart = fm.p1hp;
     global.p2HPStart = fm.p2hp;
     global.p1HP = 100;
     global.p2HP = 100;
     global.trn = 0;
}(window));

This creates an 'immediately invoked function expression'. window is passed into the function, which then attaches a number of properties to it.

You can change window to whatever object you want, such as fight.p1HP, and this function will immediately attach the listed properties to that object.

Upvotes: 1

jfriend00
jfriend00

Reputation: 708206

// initialize your own global object
if (!window.mySpace) {
    window.mySpace = {};
}

// then use it
function buildVariables(fs,fm) {
     mySpace.p1HPStart = fm.p1hp;
     mySpace.p2HPStart = fm.p2hp;
     mySpace.p1HP = 100;
     mySpace.p2HP = 100;
     mySpace.trn = 0;
  }

Then just make sure everywhere you want one of your own variables, you use your namespace in front of it:

mySpace.variableName

Note: this doesn't really "replace" the window object (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 mySpace can 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.

Upvotes: 2

Related Questions