Reputation: 382
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.
Upvotes: 1
Views: 181
Reputation: 26139
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].f.a.c();
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].f.a.c();
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.
Upvotes: 0
Reputation: 288260
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].f.a.c();
Upvotes: 1
Reputation:
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
};
Upvotes: 1