javascript get parent nested object?

2020-02-17 11:05发布

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

7条回答
\"骚年 ilove
2楼-- · 2020-02-17 11:42

It's impossible with your implementation of the object. Depends on your needs - the following implementation could be useful:

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

    },
    subobj2: {
        func1: function(){
          console.log('func1');
        },
        func2: function(){

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

        },
        func4: function(){
          this.parentObject.subobj2.func1();
        }        
    }
  }
  obj.subobj3.parentObject = obj;
/*  
  //You can also init parentObject reference of the rest of the nested objects if you need
  obj.subobj1.parentObject = obj;
  obj.subobj2.parentObject = obj;
*/  
  return obj;
}();

obj.subobj3.func4();

The idea is that nested objects can't know who is their parent, but the parent can tell its children who is he (but then init. code is needed as you can see in my implementation).

You can test it here: http://jsbin.com/eVOpITom/1/edit

查看更多
登录 后发表回答