1

I put all my code in NS, similar to how jQuery is structured. I have a few variables global to NS, that I would like to enclose and then make accessible like this -> Global.variable_name.

Below is the way I did it. Is this good practice? Is there a better way to do this where I do not have to call var Global = new GlobalMaker()

I use all capitals for global CONSTANTS.

var NS = ( function ( window, undefined ) { /* all my code is here */ } )( ) /** (including this code) *GlobalMaker */ var GlobalMaker = function() { this.tag_array = []; this.current_tag; this.validate_input_on; this.JSON_ON = 1; // selector between JSON and LON this.GATEWAY = 'class.ControlEntry.php'; // for Ajax calls this.PICTURES = '../pictures/'; // for composing tweets this.PASS = 0; this.FAIL = 1; this.NOTDEFINED = 2; }; var Global = new GlobalMaker(); /** *Global */ var Global = { tag_array: [], current_tag: 0, validate_input_on: 0, JSON_ON: 1, GATEWAY: 'class.ControlEntry.php', PICTURES: '../pictures/', PASS: 0, FAIL: 1, NOTDEFINED: 2 } 
9
  • 1
    If the object is just a collection of properties like that, you could simply initialize it with an object literal. Commented Apr 9, 2012 at 17:09
  • There's no need to call new> You can just build an object literal. var Global = {...properties...}; Commented Apr 9, 2012 at 17:10
  • Well you are creating a new instance everytime you want to access a global variable, you could make it static, but other than that, it seems good. You might find this useful: javascriptweblog.wordpress.com/2010/06/07/… Commented Apr 9, 2012 at 17:11
  • @GuyMontag: Just like the other properties. tag_array: [],, and no, the properties need values. You can use null as a substitute. Commented Apr 9, 2012 at 17:16
  • your second snippet will not work , you have typos all over the place , a semi colon , an you have to give current_tag and validate_input_on a value. Commented Apr 9, 2012 at 17:17

1 Answer 1

2

This does the equivalent, without using a constructor function:

var Global = { tag_array: [], // current_tag, // huh? // validate_input_on, // huh? JSON_ON: 1, GATEWAY: 'class.ControlEntry.php', PICTURES: '../pictures/', PASS: 0, FAIL: 1, NOTDEFINED: 2 }; 

But I don't understand the second two declarations that have no initialization.

Note, though, that if you do this as you indicate above, this Global object is available only within that outer Arc function expression. It's not truly global. Also note that the use of 'global' (lowercase) is pretty common; you might want to consider a different varialbe name (perhaps 'constants'?)

Sign up to request clarification or add additional context in comments.

Comments