How do I call parent object attribute and functions in javascript? For example, if I had an object gen0 with a child object gen1 which had a child object gen2. How would gen1 call its parents names and functions? How would gen2 call its parents and grandparents functions (without using prototypes)?
gen0 = {
name: "gen0",
gen0Func: function() {
console.log("gen0Func");
console.log("My name is " + this.name);
},
gen1: {
name: "gen1",
gen1Func: function() {
console.log("gen1Func");
console.log("My name is " + this.name);
console.log("My parents name is " + this.parent.name); // Doesn't work.
},
gen2: {
name: "gen2",
gen2Func: function() {
console.log("gen2Func");
console.log("My name is " + this.name);
console.log("My parents name is " + this.parent.name); // Doesn't work.
console.log("My grandparents name is " + this.parent.parent.name); // Doesn't work.
}
}
}
}
There's nothing that automatically links objects back to the objects that contain references to them. If you want that, you need to do it explicitly in your code.
gen0 = {
name: "gen0",
gen0Func: function() {
console.log("gen0Func");
console.log("My name is " + this.name);
},
gen1: {
name: "gen1",
gen1Func: function() {
console.log("gen1Func");
console.log("My name is " + this.name);
console.log("My parents name is " + this.parent.name); // Doesn't work.
},
gen2: {
name: "gen2",
gen2Func: function() {
console.log("gen2Func");
console.log("My name is " + this.name);
console.log("My parents name is " + this.parent.name); // Doesn't work.
console.log("My grandparents name is " + this.parent.parent.name); // Doesn't work.
}
}
}
}
gen0.gen1.parent = gen0;
gen0.gen1.gen2.parent = gen0.gen1;
gen0.gen1.gen2.gen2Func();
You should approach this in a different way. One way I would do this, is to use classes and objects with relations (parent, children, etc)..
class Gen {
constructor(name,parent) {
this.name = name;
this.parent = parent;
}
sayHi() {
console.log('Hi!.. I am ' + this.name);
}
}
var gen0 = new Gen('gen0');
var gen1 = new Gen('gen1',gen0);
var gen2 = new Gen('gen2',gen1);
gen0.sayHi(); // Hi!.. I am gen0
gen1.sayHi(); // Hi!.. I am gen1
gen1.parent.sayHi(); // Hi!.. I am gen0
gen2.parent.parent.sayHi(); // Hi!.. I am gen0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With