By Richard Powell
By Richard Powell

Reputation: 1287

Adding a namespace method to the object prototype

I am trying to add a namespace method to the Object prototype in javascript.

What I would like to be able to do is this:

var myObj = {}
myObj.namespace('nested.objects.are.created.if.not.present')

But I am getting lost. It seems quite easy to do a generic function, but not to add it to the protoype.

Here is what I have:

Object.prototype.namespace = function(ns_string) {
    var parts = ns_string.split('.');
    var parent = this;
    var i;
    var length = parts.length
    for (i = 0; i < length; i++) {
        // Create a property if it doesnt exist
        if (typeof parent[parts[i]] === "undefined") {
            parent[parts[i]] = {};
        }
        parent = parent[parts[i]];
    }
}

It appears that the value of parent is not being set correctly each time. Im sure its something very basic that I am missing, but Im not sure what it is.

Thanks in advance.

Richard

Upvotes: 0

Views: 123

Answers (1)

machineghost
machineghost

Reputation: 35790

Ok first off, as Onkelborg said, this is not a good idea (I'd even go so far as to say it's a very bad idea). Adding properties to the prototypes of core objects is just asking for trouble. Let's say you add this method, and some code on your site (could be your's, could be from a library) does:

for (var key in {foo: 'bar'}) {
    // How many times will this iterate?
}

That loop should only iterate through once, getting 'foo' as a key. In practice however it will loop twice, because your "namespace" property will show up as a property.

With that being said, if you really want to do this anyway, your basic code should work. The only thing that could mess up the value of parent is if this was off, and for that to happen you would have to invoke the method with a different "this", using foo.namespace.call(bar) or something like that.

If you're not using call (or it's sibling, apply) everything should work.

Upvotes: 1

Related Questions