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