如何在 javascript 中调用父对象的属性和函数?例如,如果我有一个对象 gen0
和一个子对象 gen1
,它有一个子对象 gen2
。 gen1
将如何调用其父项的名称和函数? gen2
将如何调用其 parent 和祖 parent 函数(不使用原型(prototype))?
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 = {
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();
关于javascript - 在javascript中调用父属性和函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49092560/