Moin
Moin

Reputation: 1143

how to get parent object property in javascript/jQuery

I've been searching a way to get the Parent object property in a nested Object but had no luck.

Here is the nested object I am using:

var obj = {
        name: 'My Name',
        obj1: {
                 age: 18,
                 name: this.name
            }
    };

But it gives and undefined error.

Is there any way in JavaScript or jQuery to achieve it?

Upvotes: 1

Views: 312

Answers (2)

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33880

You can do something like this :

var obj = new obj();

function obj(){
    var self = this;
    self.name = 'My Name';
    self.obj1 = {
        age: 18,
        name: self.name
    }
};

Upvotes: 4

Moin
Moin

Reputation: 1143

And with some jQuery love, I achieved it.

Here is the original one I was using:

var obj = {
        name: 'My Name',
        obj1: {
                 age: 18,
                 name: this.name
            }
    };

And here is my trick:

I created another object obj1Copy:

var obj1Copy = {
    name: obj.name
};

See I am using the parent object name instead of this in this copy. And then use the jQuery $.extend to merge them:

var newObj = $.extend(obj.obj1, obj1Copy);

And then use the newObj instead of obj1, like newObj.name would return My Name.

If there's any better and easy way then please share.

Upvotes: 0

Related Questions