javascript get parent nested object?

javascript, object, oop

Solution

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 :

var obj2 = {some:obj.subobj3};

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 :

obj = (function(){
    var parent = {
        subobj1: {

        },
        subobj2: {
            func1: function(){

            },
            func2: function(){

            }
        },
        subobj3: {
            func3: function(){

            },
            func4: function(){
                parent.subobj2.func1();
            }        
        }
    };
    return parent;
})();

Then you can call

obj.subobj3.func4();

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` and `prototype`, 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.

Problem

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() ?

Original source