1

Given this setup:

var ObjectNamespace   = {}
var FunctionNamespace = function FunctionNamespace() {}

ObjectNamespace.User = function() {}
FunctionNamespace.User = function User() {}

Is there anyway to write a namespace method to accomplish something like this:

ObjectNamespace.User.namespace() //=> "ObjectNamespace.User"
FunctionNamespace.User.namespace() //=> "FunctionNamespace.User"

You can get the first node by doing something like this:

ObjectNamespace.User.namespace = function() {
  return this.toString().match(/function *(\w+)/)[1]
}

ObjectNamespace.User.namespace() //=> "User"

But my question is, is there a way to reference the "parent" object, i.e. the object the User function is defined on (ObjectNamespace)? Something meta along the lines of arguments.caller.callee. That way you'd get this:

ObjectNamespace.User.namespace() //=> "ObjectNamespace.User"

Any ideas?

Lance
  • 75,200
  • 93
  • 289
  • 503

2 Answers2

2

Absolutely not. Let's assume there was, and we call it by *.parent. What would the following code do:

var apple = {}, banana = {}, lemon = {};
banana.friend = apple.friend = lemon;

lemon.parent.otherThing = 6;

console.log(apple.otherThing, banana.otherThing);

// 6, undefined?
// undefined, 6?
// 6, 6?

Who is lemon's parent? Both apple and banana are, but that doesn't make sense...

Also, your idea, while good, won't work if you call the namespace function out of context.

davin
  • 44,863
  • 9
  • 78
  • 78
0

There once was __parent__, but it's been removed. I'm not sure how it worked, see davins answer.

You might also have a look at Access parent's parent from javascript object.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375