1

I have created a function to us for namespace but how to extend its functionality

code:

MY.property = function (str, obj, prevent) {

    var ns = obj || MY,
            k = str.split(".");
    while (k.length > 1) {
        if (!prevent && typeof ns[k[0]] === "undefined") {
            ns[k[0]] = {};
        }
        if (ns[k[0]]) {
            ns = ns[k.shift()];
        } else {
            return;
        }
    }
    return [ns, [k[0]]];
};


MY.namespace = function (str) {
    var ns = this.property(str),
    k = str.split(".");
    if (k[0] === "MY") {
        k.shift();
    }
    if (ns && ns[0][ns[1]]) {
        return;
    } else {
        ns[0][ns[1]] = {};
    }
    return true;
};

This only works for MY.namespace("test") , var My.test = function(){}; but how can I extend it like this MY.namespace("test", function(){ }); and MY.namespace("test", {});

Thanks for any help or advice.

1 Answer 1

1

example

The special operator typeof should be enough to accomplish this:

My.namespace = function (str, obj) {

     if (obj) {
          this[str] = obj;
     }
     ....

My.namespace('test', function () {console.log('here');});
My.test()

EDIT: An updated example: http://jsfiddle.net/qk6Kj/1/

Sign up to request clarification or add additional context in comments.

4 Comments

Why the first obj in if (obj || typeof obj === "function")? Won't if (obj) do the same? Or, should this be just if (typeof obj === "function") to ensure that obj is a function?
@jfriend, you are right. I combined an if else statement without really thinking it through.
@joey instead of passing a another argument if I can use typeof argument[1] === "Object" || typeof argument[1] === "function since I want to pass second argument as object or function
@joey this will fail when u r passing a immediate function like MY.namespace("immediate", (function(){...}());

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.