Initializing a global namespace object

S

Stanimir Stamenkov

As the number of utility functions I write increases I've started to
use a global variable acting as namespace for my functions. Given
my functions are spread in couple of .js files and the order of
loading is not significant (documents may include random combination
of the files) I've wondered how it is best to initialize the
namespace object.

I generally use the following construct in my .js files:

(function () {
if (typeof MYNS === "undefined") {
MYNS = { };
}
// Add stuff to MYNS...
}());

But then running this through JSLint tells me: "'MYNS' is not
defined". Changing the code to:

(function () {
if (typeof this.MYNS === "undefined") {
this.MYNS = { };
}
// Add stuff to MYNS...
}());

results in no JSLint errors but then it lists 'MYNS' as member and
not a global variable, if it matters at all. Which of the both
forms is recommended? Should I just tell JSLint 'MYNS' is a
predefined global?
 
A

Asen Bozhilov

Stanimir said:
results in no JSLint errors but then it lists 'MYNS' as member and
not a global variable, if it matters at all.  Which of the both
forms is recommended?  Should I just tell JSLint 'MYNS' is a
predefined global?

Both are not good. First, because use undeclared assignment. In the
second approach the problem is in ES5 environment. The `this'
associated with that execution context in strict mode must be
`undefined'. So you will get TypeError.

I don't see any benefits by your code. The order of loading is always
mandatory and the users of your code must be know that. I have never
liked such a definition of a namespace. If I want namespace I do:

var MYNS = {};

It's enough. Should I care about third party conflicts? I don't think
so. If there are third party conflicts this means wrong usage of my
code and my recommendations. And for environment which I suggest to be
used this code I am sure that `MYNS' does not refer both host or built-
in object.

What is your native language? Is it Bulgarian?
 
R

Ry Nohryb

As the number of utility functions I write increases I've started to
use a global variable acting as namespace for my functions.  Given
my functions are spread in couple of .js files and the order of
loading is not significant (documents may include random combination
of the files) I've wondered how it is best to initialize the
namespace object.

I generally use the following construct in my .js files:

(function () {
     if (typeof MYNS === "undefined") {
         MYNS = { };
     }
     // Add stuff to MYNS...

}());

But then running this through JSLint tells me: "'MYNS' is not
defined".  Changing the code to:

(function () {
     if (typeof this.MYNS === "undefined") {
         this.MYNS = { };
     }
     // Add stuff to MYNS...

}());

results in no JSLint errors but then it lists 'MYNS' as member and
not a global variable, if it matters at all.  Which of the both
forms is recommended?  Should I just tell JSLint 'MYNS' is a
predefined global?

Use window.MYNS instead of this.MYNS, and, in order to avoid
overwriting/destroying a possibly pre-existing/previously-defined
MYNS :

window.MYNS= window.MYNS || {};

JSLint then won't complain because global vars are properties of the
global object, and the 'window' and 'self' globals are references to
the Global Object itself:

GlobalObject.window === GlobalObject.self === GlobalObject ===
(function(){return this})()

and thus window.someGlobalVarName is only an explicit way of saying
"hey, this is a global var !".
 
S

Stanimir Stamenkov

Mon, 26 Jul 2010 12:47:48 -0700 (PDT), /Asen Bozhilov/:
Both are not good. First, because use undeclared assignment. In the
second approach the problem is in ES5 environment. The `this'
associated with that execution context in strict mode must be
`undefined'. So you will get TypeError.

O.k. I understand. I generally don't have such advanced knowledge of
JavaScript. Do you know which browsers currently implement the ES5
specification and support strict mode?
I don't see any benefits by your code. The order of loading is always
mandatory and the users of your code must be know that. I have never
liked such a definition of a namespace. If I want namespace I do:

var MYNS = {};
(...)

The problem is I have a bunch of .js files which happen to be written by
multiple people and contain just "flying" global functions, and I want
to convince all the guys writing them we should at least start using a
separate space than the global object. Then we could also start
thinking of giving the code finer modularization.

So until we start making more sense of the code organization I want to
introduce a single object acting as global namespace for our own code.
And yes, the files are not loaded in random order but then different
sets of them is included in different documents, so I want more
foolproof fix for the initial namespace problem hence I need to set it
up independently in every file, but in non-destructive manner.
What is your native language? Is it Bulgarian?

Yes, I'm native Bulgarian speaking.
 
R

Ry Nohryb

Mon, 26 Jul 2010 20:18:00 +0000 (UTC), /Ry Nohryb/:



I decided to use this.MYNS instead of window.MYNS as in the given case,
and as far as my knowledge goes, 'this' should refer to the global
object and I don't really care (or want to depend) it happens to be the
'window' one having a self references as 'window' and 'self'
properties.  But as Asen Bozhilov pointed in another reply, I now see
'this' is no safer to use.  I currently have no knowledge of ES5 and how
browsers scripts should operate in that environment, but I'll probably
stick with your suggestion until I get to understand more. :)




JSLint also complained about 'window' not defined until I tell it
'window' is a predefined symbol explicitly, although I had checked the
"Assume a browser" option, also.  Is it o.k. if I do:

(function () {
     var MYNS = window.MYNS = window.MYNS || { };
     MYNS.fooBar = function () {
         // ...
     };

}());

so I don't have to qualify every MYNS reference in the closure, next?

If this code runs at the top level (if it's not wrapped in an eval()
nor inside any other function), I'd write it so:

var MYNS= window.MYNS || { };
(function () {

//Use MYNS here freely, it's already a global.

})();

The window.MYNS in the var MYNS declaration is there just to make
JSLint happy. If JSLint doesn't "hurt your feelings", you can write it
without the window. :

var MYNS= MYNS || { };

But it (JSLint) will probably complain about the use of an undeclared
MYNS because it's being used prior to its declaration.
 
R

Ry Nohryb

But it (JSLint) will probably complain about the use of an undeclared
MYNS because it's being used prior to its declaration.

Well, I mean, at that point it's -probably- undefined, but not
undeclared.
 
J

JR

As the number of utility functions I write increases I've started to
use a global variable acting as namespace for my functions.  Given
my functions are spread in couple of .js files and the order of
loading is not significant (documents may include random combination
of the files) I've wondered how it is best to initialize the
namespace object.

I generally use the following construct in my .js files:

(function () {
     if (typeof MYNS === "undefined") {
         MYNS = { };
     }
     // Add stuff to MYNS...

}());

But then running this through JSLint tells me: "'MYNS' is not
defined".  Changing the code to:

(function () {
     if (typeof this.MYNS === "undefined") {
         this.MYNS = { };
     }
     // Add stuff to MYNS...

}());

results in no JSLint errors but then it lists 'MYNS' as member and
not a global variable, if it matters at all.  Which of the both
forms is recommended?  Should I just tell JSLint 'MYNS' is a
predefined global?

Hi,
I think of (function () {})() as a means of avoiding global variables.
But if you want / need a global variable then you should follow
Jorge's advice or do that:

(function() {
var global = this;
global.MYNS = { };
// to be continued.
})();

But it seems easier to write only var MYNS = { } than the module
pattern (function() {})()
 
R

RobG

As the number of utility functions I write increases I've started to
use a global variable acting as namespace for my functions.  Given
my functions are spread in couple of .js files and the order of
loading is not significant (documents may include random combination
of the files) I've wondered how it is best to initialize the
namespace object.

I generally use the following construct in my .js files:

(function () {
     if (typeof MYNS === "undefined") {
         MYNS = { };

Don't be coy about creating global variables. If you want to create
one, declare it right up front. Just before the anonymous function,
use:

var MYNS;


Note that if MYNS already exists, the extra variable declaration has
no impact, so it is absolutely safe. Anyone reading your code will see
it right at the top and know it's yours.

     }
     // Add stuff to MYNS...

}());

But then running this through JSLint tells me: "'MYNS' is not
defined".  Changing the code to:

(function () {
     if (typeof this.MYNS === "undefined") {
         this.MYNS = { };
     }
     // Add stuff to MYNS...

Just declare it before the function.

}());

results in no JSLint errors but then it lists 'MYNS' as member and
not a global variable, if it matters at all.  Which of the both
forms is recommended?  Should I just tell JSLint 'MYNS' is a
predefined global?

If you want MYNS to be a native Object object, then you should test
explicitly for that. If you want to be strict, then the following
should run as global code:

var MYNS;
if (typeof MYNS != 'object') {
MYNS = {};
}

Now you know excatly what MYNS is (and may have stomped on someone
else's MYNS, but that's for the user of your code to fix).

Don't fall for junk like the following (which is in a commercial
product in wide use where I work):

if (dwr == null) var dwr = {};

Which infers that variables can be conditionally decalred (they can't)
and depends on the truthiness of undefined == null. The author
probably should have written:

var dwr;
if (typeof dwr == 'undefined') {
dwr = {};
}


Anyhow, it is probably sufficient to use the following as global code:

var MYNS = MYNS || {};
 
S

Scott Sauyet

As the number of utility functions I write increases I've started to
use a global variable acting as namespace for my functions.  Given
my functions are spread in couple of .js files and the order of
loading is not significant (documents may include random combination
of the files) I've wondered how it is best to initialize the
namespace object.

I've had to do this a number of times recently, and this has served my
purposes well:

var MYNS = MYNS || {};

at the top of each JS file that uses the namespace. And I simply tell
JSLint that this is a global variable.

When I can't put the global namespace in a JSLint configuration file,
I often format it as

/* global MYNS */ var MYNS = MYNS || {};

to keep it to a single line.

That seems fairly simple, and I don't know if there are any underlying
issues that I haven't considered, but it works well for me.
 
D

David Mark

Use window.MYNS instead of this.MYNS, and, in order to avoid
overwriting/destroying a possibly pre-existing/previously-defined
MYNS :

window.MYNS= window.MYNS || {};

You've finally lost it, haven't you Jorge?

var MYNS;

if (!MYNS) {
MYNS = {};
}

Or:-

var MYNS;

MYNS = MYNS || {};

JSLint then won't complain because global vars are properties of the
global object, and the 'window' and 'self' globals are references to
the Global Object itself:

Not that it matters a whit, but last I checked, JSLint decried the use
of - window - as an "implied global". (!)
GlobalObject.window === GlobalObject.self === GlobalObject ===
(function(){return this})()

As you've been told a thousand times, that proves nothing.
and thus window.someGlobalVarName is only an explicit way of saying
"hey, this is a global var !".

Get better Jorge!
 
D

David Mark

Both are not good. First, because use undeclared assignment. In the
second approach the problem is in ES5 environment. The `this'
associated with that execution context in strict mode must be
`undefined'. So you will get TypeError.

I don't see the strict mode problem to be an issue as you would have
to explicitly require strict mode in the code.
 
D

David Mark

If this code runs at the top level (if it's not wrapped in an eval()
nor inside any other function), I'd write it so:

And JFTR, there is no reason at all that such code should be inside of
an anonymous one-off function.
var MYNS= window.MYNS || { };

Really?! That's not progress, Jorge.
(function () {

  //Use MYNS here freely, it's already a global.

})();

The window.MYNS in the var MYNS declaration is there just to make
JSLint happy.

For one, making JSLint "happy" is not a prerequisite. You can't take
arbitrary orders from a script, you need to think about what you are
doing. Granted, *most* of JSLint's missives are useful.
If JSLint doesn't "hurt your feelings", you can write it
without the window. :

var MYNS= MYNS || { };

As mentioned, the competent version is:-

var MYNS;

if (!MYNS) {
MYNS = {};
}

....or:-

var MYNS;

MYNS = MYNS || {};

You seem to be fouling this up in some sort of ill-advised quest to
cram the whole thing on to one line. Leave that to the minifier. ;)
But it (JSLint) will probably complain about the use of an undeclared
MYNS because it's being used prior to its declaration.

I guarantee to you JSLint won't say a peep about either of the
versions I posted. In your mind, wouldn't that make them correct? :)
 
D

David Mark

Well, I mean, at that point it's -probably- undefined, but not
undeclared.

You know, for somebody who decries the "decline" of this newsgroup,
you should know that waffling over such a simple question/answer is
not helping matters at all. ;)
 
D

David Mark

Don't be coy about creating global variables. If you want to create
one, declare it right up front. Just before the anonymous function,
use:

  var MYNS;

Note that if MYNS already exists, the extra variable declaration has
no impact, so it is absolutely safe. Anyone reading your code will see
it right at the top and know it's yours.



Just declare it before the function.



If you want MYNS to be a native Object object, then you should test
explicitly for that. If you want to be strict, then the following
should run as global code:

  var MYNS;
  if (typeof MYNS != 'object') {
    MYNS = {};
  }

Forgot the check for null:-

var MYNS;
if (!MYNS || typeof MYNS != 'object') {
  MYNS = {};
}
Now you know excatly what MYNS is (and may have stomped on someone
else's MYNS, but that's for the user of your code to fix).

Don't fall for junk like the following (which is in a commercial
product in wide use where I work):

  if (dwr == null) var dwr = {};

Dojo-esque. :( You know they un-declared all of their globals about
a year ago because somebody suggested it would be "faster". :)
Which infers that variables can be conditionally decalred (they can't)
and depends on the truthiness of undefined == null. The author
probably should have written:

  var dwr;
  if (typeof dwr == 'undefined') {
    dwr = {};
  }

Or just used boolean type conversion as any "falsey" value is going to
be undesirable.

var dwr;

if (!dwr) {
dwr = {};
}
Anyhow, it is probably sufficient to use the following as global code:

  var MYNS = MYNS || {};

That will work as well. I don't particularly care for it, but that's
a matter of personal taste.
 
S

Scott Sauyet

David said:
That will work as well.  I don't particularly care for it, but that's
a matter of personal taste.

The one practical advantage to it I know of is that it's much easier
to introduce it in the sort of environment the OP describes, when
there is a team that needs to be convinced that namespaces are not
difficult. It's easy to point to a one-liner to demonstrate how easy
it is to start using namespaces.
 
D

David Mark

The one practical advantage to it I know of is that it's much easier
to introduce it in the sort of environment the OP describes, when
there is a team that needs to be convinced that namespaces are not
difficult.  It's easy to point to a one-liner to demonstrate how easy
it is to start using namespaces.

If the team is having trouble wrapping their brains around global
variable declarations (a la Jorge), then they've got bigger problems
to sort out. They should also understand that there is no such thing
as a "namespace" in JS. It's a global variable referencing an
object. Calling it something else implies that it is somehow
different from all other native objects, which it is not. That's
where the confusion starts.
 
S

Stanimir Stamenkov

Tue, 27 Jul 2010 00:57:31 +0000 (UTC), /RobG/:
Don't be coy about creating global variables. If you want to create
one, declare it right up front. Just before the anonymous function, use:

var MYNS;

Note that if MYNS already exists, the extra variable declaration has
no impact, so it is absolutely safe. Anyone reading your code will see
it right at the top and know it's yours.

Ah, thanks. I was not sure whether the duplicate declaration in
different files would be permissible, i.e. it wouldn't destroy the value
of previously declared and initialized variable. I should have just
tried it, but it is good to know it is all right in theory, too.
Anyhow, it is probably sufficient to use the following as global code:

var MYNS = MYNS || {};

So I'll stick with this at the beginning of the file.
 
R

RobG

Tue, 27 Jul 2010 00:57:31 +0000 (UTC), /RobG/:




Ah, thanks.  I was not sure whether the duplicate declaration in
different files would be permissible, i.e. it wouldn't destroy the value
of previously declared and initialized variable.  I should have just
tried it, but it is good to know it is all right in theory, too.

You could always read the specification[1]: ECMA-262 ed 3, §10.1.3
Variable Instantiation, the last part of which says:

"If there is already a property of the variable object with
the name of a declared variable, the value of the property
and its attributes are not changed. ... In particular, if a
declared variable has the same name as a declared function
or formal parameter, the variable declaration does not
disturb the existing property"

So I'll stick with this at the beginning of the file.

Of *each* file. ;-)


1. It's always good to find the relevant part of the spec to confirm
things. It's not an easy document to read and comprehend (I find it
quite difficult). If you keep using it as a reference, and search or
ask here if there are things you can't find or figure out, then bit by
bit it starts to make sense (mostly).
 
S

Stanimir Stamenkov

Tue, 27 Jul 2010 07:09:41 +0000 (UTC), /RobG/:
Of *each* file. ;-)

Yes, my mistake. I've really meant "at beginning of each file". :)
1. It's always good to find the relevant part of the spec to confirm
things. It's not an easy document to read and comprehend (I find it
quite difficult). If you keep using it as a reference, and search or
ask here if there are things you can't find or figure out, then bit by
bit it starts to make sense (mostly).

Seems the best way to go. Thank you and the rest who provided
valuable guidance.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,838
Latest member
KandiceChi

Latest Threads

Top