简体   繁体   中英

JavaScript access parent element

I need to access a variable of a containing element in a function of the child element. How can I achieve this?

object = {
    a : {
        c : function() {
            //need to access b here
        },
        d : 2
    },
    b : 1
};

In this case I need to access the variable b in the function c . I tried some variations with bind() but nothing worked. The question JavaScript access parent object attribute doesn't work for me. I can't reach the variable object , because the object is deeper nested.

Make a into a getter.

object = {
    get a() {
      var self = this;
      return {
        c: function() {
           return self.b;
        },
        d: 2
      }
    },
    b : 1
};

Or, if c doesn't need a this to refer to d , for example, then

object = {
    get a() {
      return {
        c: () => this.b,
        d: 2
      }
    },
    b : 1
};

It doesn't matter that object is deeply nested. Just use object.b .

 var object; ([{a:[{b:[{c:[{d:[{e:[{f: // deeply nested object = { a: { c: function() { console.log(object.b); }, d: 2 }, b: 1 } }]}]}]}]}]}])[0].a[0].b[0].c[0].d[0].e[0].fac(); 

I like Oriol's answer. :-)

Another alternative to use a closure.

 ([{a:[{b:[{c:[{d:[{e:[{f: // deeply nested (function (){ var object = { a: { c: function() { console.log(object.b); }, d: 2 }, b: 1 } return object; })() }]}]}]}]}]}])[0].a[0].b[0].c[0].d[0].e[0].fac(); 

Or you can move the object creation to a separate function if that makes sense (you can name that function).

 function createHierarchy(){ return ([{a:[{b:[{c:[{d:[{e:[{f:createObject()}]}]}]}]}]}]); } function createObject(){ var object = { a: { c: function() { console.log(object.b); }, d: 2 }, b: 1 } return object; } var hierarchy = createHierarchy(); hierarchy[0].a[0].b[0].c[0].d[0].e[0].fac(); 

Using a DI container is just a single step from here. :-P

It may happen that you need a graph instead of a hierarchy and your model is completely wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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