[英]javascript calling parent method from child
I have the following object: 我有以下对象:
var party =
{
food:
{
serve: function () {
// I want to call turnOff method from here
}
cleanUp: function () {
}
}
music:
{
turnOff: function () {
}
}
}
So as the comment points out, I want to call the turnOff method from the music object, how can I do this? 所以评论指出,我想从音乐对象中调用turnOff方法,我该怎么做?
this
refers to the food object but I need to access the music object... this
是指食物对象,但我需要访问音乐对象......
Use a constructor instead of a literal with a variable referencing the parent object 使用构造函数而不是带有引用父对象的变量的文字
var party = new (function()
{
var self = this;
this.food =
{
serve: function () {
self.music.turnoff();
},
cleanUp: function () {
}
}
this.music =
{
turnOff: function () {
}
}
})();
var party =
{
food:
{
serve: function () {
party.music.turnOff();
},
cleanUp: function () {
}
},
music:
{
turnOff: function () {
}
}
}
Call it as party.music.turnOff
(). 将其称为
party.music.turnOff
()。
FYI, your above code block isn't valid. 仅供参考,您的上述代码块无效。 You're missing some commas - after the
serve
and food
closing braces. 在
serve
和food
关闭括号后,你会遗漏一些逗号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.