Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript get parent nested object?

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

like image 613
Joe Avatar asked Nov 23 '12 18:11

Joe


2 Answers

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.

like image 88
Denys Séguret Avatar answered Oct 07 '22 12:10

Denys Séguret


Here's how you can add .parent to any sub-object with a recursive init:

var obj = {
    init: function() {
        for (var i in this) {
            if (typeof this[i] == 'object') {
                    this[i].init = this.init;
                    this[i].init();
                    this[i].parent = this;
            }
        }
        return this;
    },
    subobj1: {
    },
    subobj2: {
        func1: function(){
            console.log('hey');
        },
        func2: function(){
        }
    },
    subobj3: {
        func3: function(){
        },
        func4: function(){
            this.parent.subobj2.func1();
        }        
    }
}.init();

obj.subobj3.func4();

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:

this.parent.parent.subobjX.funcY();

http://jsbin.com/yuwiducadoma/1/watch?js,console

like image 25
S01ds Avatar answered Oct 07 '22 12:10

S01ds