This is continuation of my earlier post on namespaces. We saw how to implement namespace for JavaScript. How about a feature equivalent to Java's import (or C++ using)? We can implement something like:
/**
* imports all or subset of names from given namespace.
*
* @param ns namespace
* @param patten names matching this pattern will be imported
* pattern is optional. If not specified, all names are
* imported (like Java's import package_name.*).
*/
function using(ns, pattern) {
if (pattern == undefined) {
// import all
for (var name in ns) {
this[name] = ns[name];
}
} else {
if (typeof(pattern) == 'string') {
pattern = new RegExp(pattern);
}
// import only stuff matching given pattern
for (var name in ns) {
if (name.match(pattern)) {
this[name] = ns[name];
}
}
}
}
Sample script that uses namespace and using:
var ns = namespace("function p() { print('p'); }; function s() { print('s'); }");
ns.p(); // call 'p' in namespace 'ns'
using(ns); // import all from namespace 'ns'
p(); // call ns.p()
s(); // call ns.s();
Another script sample that uses imports subset:
var ns = namespace("function p() { print('p'); }; function s() { print('s'); }");
ns.p(); // call 'p' in namespace 'ns'
using(ns, /p.*/); // import only the names matching
p(); // call ns.p()
ns.s(); // call ns.s() -- but can only use qualified name
Thanks Alex. I had a typo (missing double quote) in namespace call
Posted by Alex on November 21, 2005 at 03:27 AM IST #