简体   繁体   English

JavaScript访问父元素

[英]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 . 在这种情况下,我需要访问函数c的变量b I tried some variations with bind() but nothing worked. 我用bind()尝试了一些变体,但没有任何效果。 The question JavaScript access parent object attribute doesn't work for me. JavaScript访问父对象属性问题对我不起作用。 I can't reach the variable object , because the object is deeper nested. 我无法到达变量object ,因为该对象嵌套得更深。

Make a into a getter. 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 或者,例如,如果c不需要this来引用d ,则

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

It doesn't matter that object is deeply nested. object被深嵌套并不重要。 Just use object.b . 只需使用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. 我喜欢Oriol的回答。 :-) :-)

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. 从这里开始,使用DI容器只是一个步骤。 :-P :-P

It may happen that you need a graph instead of a hierarchy and your model is completely wrong. 您可能需要而不是层次结构,并且模型完全错误。

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

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