I have an object like this for example:
obj = {
subobj1: {
},
subobj2: {
func1: function(){
},
func2: function(){
}
},
subobj3: {
func3: function(){
},
func4: function(){
}
},
}
How do I call func1 from within func4 without having to call obj.subobj2.func1() ?
Here's how you can add
.parent
to any sub-object with a recursive init:With this solution you can also use
.parent
as many times as your nesting requires, like for instance if you had two levels of nesting:http://jsbin.com/yuwiducadoma/1/watch?js,console
As others have said, with a plain object it is not possible to lookup a parent from a nested child.
However, it is possible if you employ recursive ES6 Proxies as helpers.
I've written a library called ObservableSlim that, among other things, allows you to traverse up from a child object to the parent.
Here's a simple example (jsFiddle demo):
Here is an asnwer more
ActionScript
like and easily to understand:Just remember that an object can't have multiple parents.
You can't exactly. You have no mean to know in what objects your function exists.
Note that it could be in more than one : you could have written this after your existing code :
So there can't be a unique link (and there is no accessible link) from a property value to the object holding it.
Now, supposing you'd be satisfied with a link made at object creation, you could use a factory to build your object :
Then you can call
Demonstration
EDIT
I see you gave the tag OOP to your question. You should know that the pattern I gave is more frequently used to define modules. OOP in javascript is more often done using
new
andprototype
, in order to enable instances sharing methods and inheritance. As you probably want modules rather than OOP, you seem to be fine, though.See this introduction.
That isn't possible. Object properties are obtain by the object through which they are set. JavaScript doesn't implicitly set the root object as global, and therefore you can't alias
obj.subobj2.func1
asfunc1
or in any way shorter. If you find yourself calling that function excessively, try setting a variable instead.You can't do that directly, since there is no way to "go up" the object hierarchy like you can with ".." in a filesystem.
What you can do is have variables pointing to the subobjects or subfunctions directly, so that you don't need to go through the hierarchy to call them. The following is a common pattern for creating Javascript modules:
In this example, the inner functions can access
obj1
,obj2
,func3
andfunc4
directly from their variables. The self-calling function makes so these inner variables are private and hidden from the outside and the return statement allows you to export only the functions that you want to make public.