On Apr 6, 10:47 pm, ben <[email protected]> wrote:
> No one likes globals in javascript.

Any non-trivial script will probably have some global variables>
Therefore we group our variables and function in a namespace

What? You're using a detested global variable! :-)

A "namespace" object doesn't provide any more safety from naming
conflicts than using all globals. e.g.

  var myLib = {
    myNamespacedMethod : function(){...}
  };

is no more conflict safe than:

  var myLib_myNamespacedMethod = function(){...}

in fact it's even *more* likely to have conflicts since any the entire
myLib object might be replaced rather than just the conflicting method
names.

It is a good idea to use names that are unlikely to conflict with
others though.


> or wrap
> all our code in a anonymous function to  prevent global.

That isn't always suitable.

> However there are certain situation that we might need to use global.
> For example when our project is growing bigger and we have to split
> our code into modules and save them in different files.
> Therefore I wrote this jQuery plugin call  jQuery Secret to solve it.

jQuery adds a couple of global variables. "$" is probably the most
commonly used variable name by libraries so you are increasing your
chances of conflict more by using it than using some other name.


[...]
> Actually it's got nothing to do with jquery
> I just did not want to create another namespace
> and jquery is popular so I wrap the code under jquery's namespace

The jQuery object (v 1.5.1) has 97 properties and every jQuery plugin
will add properties to various parts of the jQuery object. So you are
about as likely to get naming conflicts by adding to the $ variable as
using global objects.

To avoid conflict with random properties being added with various
"namespaces", you need a naming strategy that is unlikely to conflict
with any others (such as a 3 or 4 letter prefix). And if that naming
strategy is sufficient to avoid conflicts with those on the jQuery
object (either the standard ones or those added by plugins) it will
likely be sufficient in the global space also.

Global variables aren't inherently bad, javascript would be quite
limited without them. There are good and bad approaches for their use,
but that is up to the programmer or application designer and poor
naming is poor naming, regardless of whether it is implemented
globally or as object properties.


--
Rob

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to