Hey Hudz,

Well, here you're basically using "nc" (which coding standards may prefer to see capitalized to indicate it's not a mere variable, perhaps…) as a namespace.

Clearly you don't intend to instantiate it or do other OOP-related stuff with it; you're just trying not to pollute the global scope, which is a good idea!

So you don't need to do anything more with it. However, your code is contradictory:

  var nc = nc || {};

OK, so you're trying NOT to overwrite an existing nc object. Except you're putting this inside a var statement, which doesn't make much sense in an otherwise global scope. "var" is intended to make variables function-local. So just skip it:

  nc = nc || {};

Second, after taking such care to preserve an existing object, you're overwriting it entirely!

  nc = …

That won't do. Because you just ensured nc existed, either freshly created (using the empty object literal {}) or already there, just change its alert property:

  nc.alert = function alert(obj) { window.alert(obj); }

Here, using a Named Function Expression here: function alert(obj), is not necessary; you could go with an anonymous function as in your original code.

However, I favor NFE's as these make for clearer call stacks when debugging code, naming as many stack frames as possible. However, this also means you must be careful to explictly state which "alert" function you're calling *inside* (the "global", window-provided one, in this case), as NFE's create an identifier visible in their local scope (the body of the function), so just saying "alert" in there will lead to infinite recursion, ending up with a stack overflow ("Stack level too deep" error message).

As a final word of advice, your resorting to the global, window-provided alert function won't help you much with objects: most JS runtimes will only say "[object Object]". You may need another helper, or to write your own piece of code, perhaps based on a for…each loop, to display the internals of the object you're given, unless it's a built-in object type that window.alert already knows how to render.

'HTH,

--
Christophe Porteneuve

_______________________________________________
JSMentors mailing list
JSMentors@jsmentors.com
http://jsmentors.com/mailman/listinfo/jsmentors_jsmentors.com

Reply via email to