Javascript objects: get parent [duplicate]

2019-01-01 03:27发布

This question already has an answer here:

I have the following (nested) object:

obj: { subObj: { foo: 'hello world' } };

Next thing I do is to reference the subobject like this:

var s = obj.subObj;

Now what I would like to do is to get a reference to the object obj out of the variable s. Something like:

var o = s.parent;

Is this somehow possible?

标签: javascript
12条回答
骚的不知所云
2楼-- · 2019-01-01 04:02

This is an old question but as I came across it looking for an answer I thought I will add my answer to this to help others as soon as they got the same problem.

I have a structure like this:

var structure = {
    "root":{
        "name":"Main Level",
        nodes:{
            "node1":{
                "name":"Node 1"  
            },
            "node2":{
                "name":"Node 2"  
            },
            "node3":{
                "name":"Node 3"  
            }
        }
    }
}

Currently, by referencing one of the sub nodes I don't know how to get the parent node with it's name value "Main Level".

Now I introduce a recursive function that travels the structure and adds a parent attribute to each node object and fills it with its parent like so.

var setParent = function(o){
     if(o.nodes != undefined){
          for(n in o.nodes){
              o.nodes[n].parent = o;
              setParent(o.nodes[n]);
          }
     }
}

Then I just call that function and can now get the parent of the current node in this object tree.

setParent(structure.root);

If I now have a reference to the seconds sub node of root, I can just call.

var node2 = structure.root.nodes["node2"];
console.log(node2.parent.name);

and it will output "Main Level".

Hope this helps..

查看更多
牵手、夕阳
3楼-- · 2019-01-01 04:03

There is a more 'smooth' solution for this :)

var Foo = function(){
  this.par = 3;

  this.sub = new(function(t){ //using virtual function to create sub object and pass parent object via 't'
    this.p = t;
    this.subFunction = function(){
      alert(this.p.par);
    }
  })(this);
}

var myObj = new Foo();
myObj.sub.subFunction() // will popup 3;

myObj.par = 5;
myObj.sub.subFunction() // will popup 5;
查看更多
萌妹纸的霸气范
4楼-- · 2019-01-01 04:03

Just in keeping the parent value in child attribute

var Foo = function(){
    this.val= 4;
    this.test={};
    this.test.val=6;
    this.test.par=this;
}

var myObj = new Foo();
alert(myObj.val);
alert(myObj.test.val);
alert(myObj.test.par.val);
查看更多
姐姐魅力值爆表
5楼-- · 2019-01-01 04:06

A nested object (child) inside another object (parent) cannot get data directly from its parent.

Have a look on this:

var main = {
    name : "main object",
    child : {
        name : "child object"
    }
};

If you ask the main object what its child name is (main.child.name) you will get it.
Instead you cannot do it vice versa because the child doesn't know who its parent is.
(You can get main.name but you won't get main.child.parent.name).

By the way, a function could be useful to solve this clue.
Let's extend the code above:

var main = {
    name : "main object",
    child : {
        name : "child object"
    },
    init : function() {
        this.child.parent = this;
        delete this.init;
        return this;
    }
}.init();

Inside the init function you can get the parent object simply calling this.
So we define the parent property directly inside the child object.
Then (optionally) we can remove the init method.
Finally we give the main object back as output from the init function.

If you try to get main.child.parent.name now you will get it right.
It is a little bit tricky but it works fine.

查看更多
余生无你
6楼-- · 2019-01-01 04:08

You will need the child to store the parents this variable. As the Parent is the only object that has access to it's this variable it will also need a function that places the this variable into the child's that variable, something like this.

var Parent = {
  Child : {
    that : {},
  },
  init : function(){
    this.Child.that = this;
  }
}

To test this out try to run this in Firefox's Scratchpad, it worked for me.

var Parent = {
  data : "Parent Data",

  Child : {
    that : {},
    data : "Child Data",
    display : function(){
      console.log(this.data);
      console.log(this.that.data);
    }
  },
  init : function(){
    this.Child.that = this;
  }
}

Parent.init();
Parent.Child.display();
查看更多
谁念西风独自凉
7楼-- · 2019-01-01 04:10

I have been working on a solution to finding the parent object of the current object for my own pet project. Adding a reference to the parent object within the current object creates a cyclic relationship between the two objects.

Consider -

var obj = {
    innerObj: {},
    setParent: function(){
        this.innerObj.parent = this;
    }
};
obj.setParent();

The variable obj will now look like this -

obj.innerObj.parent.innerObj.parent.innerObj...

This is not good. The only solution that I have found so far is to create a function which iterates over all the properties of the outermost Object until a match is found for the current Object and then that Object is returned.

Example -

var obj = {
    innerObj: {
        innerInnerObj: {}
    }
};

var o = obj.innerObj.innerInnerObj,
    found = false;

var getParent = function (currObj, parObj) {
    for(var x in parObj){
        if(parObj.hasOwnProperty(x)){
            if(parObj[x] === currObj){
                found = parObj;
            }else if(typeof parObj[x] === 'object'){
                getParent(currObj, parObj[x]);
            }
        }
    }
    return found;
};

var res = getParent(o, obj); // res = obj.innerObj

Of course, without knowing or having a reference to the outermost object, there is no way to do this. This is not a practical nor is it an efficient solution. I am going to continue to work on this and hopefully find a good answer for this problem.

查看更多
登录 后发表回答