Thanks! I knew eval was bad, that's why I'd posted it here. :)
On Dec 17, 2:24 pm, Ariel Flesler <afles...@gmail.com> wrote: > No eval() please! > > function namespace(name, data){ > data = data || window; > name = name.split("."); > > for (var i=0; i < name.length; i++) { > var ns = name[i]; > data = data[ns] || ( data[ns] = {} ); > } > return data; > > }; > > It'd a little get shorter if you use jQuery.each. > > Cheers > > -- > Ariel Fleslerhttp://flesler.blogspot.com/ > > On Dec 17, 8:05 pm, Kean <shenan...@gmail.com> wrote: > > > I wrote a simple namespacer. Do you think this is useful in real world > > applications? Any improvements that can be made to the code? Thank > > you. > > > var namespace = function (name, global){ > > var root = global || '$'; > > > (!eval('window.'+root))? eval('window.' + root + '={}') : ''; > > > var name = name.split("."); > > var fullname; > > for (var i=0; i<name.length; i++) { > > fullname = (!i) ? name[i] : fullname + "." + name[i]; > > if (!eval (root + "." + fullname)) > > eval (root + "." + fullname + " = {}"); > > } > > > } > > > namespace('hello.yahoo'); > > namespace('helloz.yahoo2'); > > namespace('helloz.yahoo2', 'YAHOO'); > > > $.hello.yahoo.init = function() { alert(1); }; > > $.helloz.yahoo2.init = function() { alert(2); }; > > YAHOO.helloz.yahoo2.init = function() {alert(3); }; > > > $.hello.yahoo.init(); //alerts 1 > > $.helloz.yahoo2.init(); // alerts 2 > > YAHOO.helloz.yahoo2.init(); // alerts 3