tags:

views:

42

answers:

4

Hi It is good practice to create one unique global object that wrap the functions and properties inside this object.I look up a lot of sample code and see code like this

if(!myglobalObject) myglobalObject ={};

However , this code does not work ,I got an error saying ReferenceError: myglobalObject is not defined Can anyone shed some light on why I got the error?

A: 
if (myglobalObject == null) myglobalObject = {}
Júlio Santos
The non-strict check makes this more or less the same as what the OP tried, but the real problem is that attempting to access an undeclared variable will throw an error in ECMAScript.
Andy E
A: 

if (window['myglobalObject'] === undefined) window.myglobalObject = {};

If you don't want to expose your object from context you can do smth like this:

var myglobalObject = myglobalObject || {};

Gleb M Borisov
+2  A: 
if (typeof myglobalObject === 'undefined') var myglobalObject = {};
Q_the_dreadlocked_ninja
Assignment to an undeclared variable (as you're doing here) will cause an error in ECMAScript 5 strict mode. Use a `var` statement instead.
Tim Down
Good point, edited.
Q_the_dreadlocked_ninja
+1  A: 

To avoid errors in ECMAScript 5 strict mode, you need to use var to define all variables:

if (typeof myglobalObject == "undefined") {
    var myglobalObject = {};
}

The other alternative is to assign a property to the global object:

// The following line gets you a global object in any ECMAScript environment.
// In browsers, you could just use window.
var globalObj = (function() { return this; })();
if (typeof globalObj.myglobalObject == "undefined") {
    globalObj.myglobalObject = {};
}
Tim Down