0

My present namespacing is like this

var MY = MY || {};
MY.namespace = function(str){};

So basically, you can just create MY.namespace("new"); and then My.new = function(){};

But now, I want to pass a second parameter like MY.namespace("new", function(){});. How can I achieve this approach?

edit1:

var MY.namespace = function(ns_string){
     var parts = ns_string.split('.'),
         parent =MY,i;
     if(parts[0]==="MY"){
         parts = parts.slice(1);
     }

     for(i=0; i< parts.length ;i++){
         if (typeof parent[parts[i]] ==="undefined"){
             parent[parts[i]] ={};
         }

         parent = parent[parts[i]];
     }
     return parent;
};

3 Answers 3

0

You can use:

My.namespace = function(fnName, fnBody) {
  My[fnName] = fnBody;
}

e.g.

My.namespace('sayHi', function(){alert('hi');});
My.sayHi();
1
  • check my updated namespace function ...its now just work like MY.namespace("sayHi"); not MY.namespace("sayHi", function(){});
    – paul
    Aug 4, 2011 at 23:54
0

JavaScript doesn't put restrictions on the number of arguments to the function. The arguments object in the function can be used to access all arguments passed to the function in an array-like fashion, even if they are not named in the parameter list:

My.namespace = function(fnName) {
    // arguments[0] gives us the same things as fnName
    // however, using indexes from 1 to (arguments.length-1)
    // gives the other (nameless) parameters
}
0
0

Not sure if this is what you mean. Taking into account your edit, Kevin's resopnse and what you seem to suggest in your comments, you might mean this:

var MY = {};
MY.namespace = function(ns_string, fnBody){
 var parts = ns_string.split('.'),
     parent =MY,i,
     last = parts.slice(parts.length-1);

 console.log(parent);
 if(parts[0]==="MY"){
     parts = parts.slice(1);
 }

 if (parts.length !== 1) {
     parts = parts.slice(0, parts.length-1);
 }

 for(i=0; i< parts.length ;i++){
     if (typeof parent[parts[i]] ==="undefined"){
         parent[parts[i]] ={};
     }

     parent = parent[parts[i]];
 }
 parent[last] = fnBody;
 return parent;
};

This would work like

> MY.namespace('ns1.ns2.myFn', function(console.log('this is myFn')));
> MY.ns1.ns2.myFn();
this is myFn
2
  • will it work if i just say MY.namespace("ns1"); and than MY.namespace = function(){};
    – paul
    Aug 5, 2011 at 3:58
  • sorry typo in my last comment should be MY.ns1 = function(){};
    – paul
    Aug 5, 2011 at 4:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.