views:

51

answers:

4

I have the following namespace (com.myCompany.myProject):

var com = {
  myCompany: {
    myProject: {
      x: 1,
      y: 2,
      o: function() {
      }
    }
  }
};

For example, I have the following code:

var self = com.myCompany.myProject;

How can I show this namespace as a string, e.g. "com.myCompany.myProject" ?

I've tried JSON.stringify() but it isn't that I looked for.

Thanks,

A: 

self.toString()

elementvine
No, it's just returns "[object Object]"
Alex Ivasyuv
ugh.. duh.. I'm sorry, wasn't thinking it through.. or reading it through.
elementvine
+1  A: 

It's not possible. An object has no way of knowing where it is stored.

If you need this kind of functionality, you have to store it somewhere in the object.

var com = {
  myCompany: {
    myProject: {
      x: 1,
      y: 2,
      '_namespace': 'com.myCompany.myProject',
      o: function() {
      }
    }
  }
};
seanizer
+1  A: 

As seanizer says, this is not possible. Here are some related things that are possible, though:

index property as a string:

var self = com["myCompany"]["myProject"];

// or even...
var myCo = "myCompany";
var myPr = "myProject";
var self = com[myCo][myPr];
alert(myCo + "." + myPr);

get all properties of an object as strings:

for(var p in com) {
    alert(p.toString());
}

Will either of those help you?

Gabe Moothart
A: 

This may not be exactly what you need, but hey, it may. Ext has a method called Ext.namespace, aliased as Ext.ns. It works like the following

Ext.ns('com.app.package'); com.app.package.Clazz = function() {};

http://dev.sencha.com/deploy/dev/docs/source/Ext.html#method-Ext-namespace

If this will help you, use their source code as inspiration.

Juan Mendes
Yeah, I know. I used it before, very useful. But it doesn't that I looked for.
Alex Ivasyuv