简体   繁体   English

如何在javascript / jQuery中获取父对象属性

[英]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. 我一直在寻找一种方法来获取嵌套对象中的Parent对象属性,但没有运气。

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. 但它给出了undefined错误。

Is there any way in JavaScript or jQuery to achieve it? 在JavaScript或jQuery中有没有办法实现它?

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
    }
};

And with some jQuery love, I achieved it. 有了一些jQuery的爱,我实现了它。

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 : 我创建了另一个对象obj1Copy

var obj1Copy = {
    name: obj.name
};

See I am using the parent object name instead of this in this copy. 请参阅我在此副本中使用父对象名称而不是this对象名称。 And then use the jQuery $.extend to merge them: 然后使用jQuery $.extend来合并它们:

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

And then use the newObj instead of obj1 , like newObj.name would return My Name . 然后使用newObj而不是obj1 ,就像newObj.name将返回My Name

If there's any better and easy way then please share. 如果有更好更简单的方法请分享。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM