using namespace in JavaScript

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
Comments:

I think you have missed some double quotes in your sample scripts ;)

Posted by Alex on November 20, 2005 at 07:27 PM IST #

Post a Comment:
Comments are closed for this entry.
About

sundararajan

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today
Bookmarks
Links

No bookmarks in folder

Blogroll

No bookmarks in folder

News

No bookmarks in folder