I use this function to create namespaces:
var namespace = function(ns) {
var scope = window;
var tokens = ns.split(".");
for (var idx = 0, len = tokens.length; idx < len; idx++) {
var token = tokens[idx];
scope = scope[token] = scope[token] || {};
}
};
For example: namespace("Zen.Ui");
Re:Advanced JavaScript Techniques
by woadwarrior01 on Friday October 09, 2009 @06:20PM
(#872584)
YAHOO.namespace in YUI does the same thing, except that it creates everything under the YAHOO namespace.
Clever! How do you add your properties and methods? Another clever trick?
Thanks for sharing your rule of thumb. I have observed that inevitably most objects/functions require three 'groups' of variables, more or less I use this pattern and I would appreciate your thoughts.
- Defaults: Must be defined within the object literal
- User Options : part of the function arguments
(user can use an object literal,
anon function etc.)
- Settings : The actual mixin used by the methods
function aProblem(arg1, arg2, options){
// define the necessary defaults
var defaults={} //define defaults
// use a mixin algo to combine options and
// defaults
var settings = mixin(options, defaults);
// main function routines
var myObj={};
return myObj={
property1 : settings.property1,
property2 : settings.property2
}
}
Re:Advanced JavaScript Techniques
by willwagner on Friday October 09, 2009 @02:21PM
(#872113)
I use a similar technique when the number of optional arguments get out of control (i.e. if there is more than one optional argument). If you want to tight control, you can take advantage of the fact that a variable that is a function, the length member specifies the number of arguments declared as in:
(function(a,b,c){}).length == 3
Using that knowledge, you can do this at the top of a function:
if(arguments.callee.length > arguments.length){ throw "Required Parameter Missing"; }
In his namespace example, also, he uses the new Object() notation, which is not nearly as concise as var foo = {}, which does the same exact thing (similarly, var arr = [] is better than var arr = new Array()).
We could rewrite the entire namespace initialization block as:
var MY = (MY) ? MY : { CUSTOM : {} };
This sets the variable MY to itself if it exists, otherwise assign an object literal that has a member property CUSTOM that happens to be an empty object. You could now create a new function, say, MY.CUSTOM.foo = function() { alert('foo'); };