[英]How can I refer to a parent from a child?
The wording of the title probably needs re-visiting, but for now consider the following code: 标题的措词可能需要重新访问,但现在考虑以下代码:
var ParentControl = function()
{
this.ShowAlert = function()
{
alert('hi!');
}
this.childControl = new ChildControl();
};
var ChildControl = function()
{
// IN THIS SCOPE HERE I NEED TO CALL 'ShowAlert'
};
var parentControl = new ParentControl();
As per the comment in the code snippet above, I need instances of ChildControl
to call the 'ShowAlert' function of their parent but I don't know how. 根据上面的代码片段中的注释,我需要
ChildControl
实例来调用其父级的“ ShowAlert”功能,但我不知道该怎么做。
What I've Tried 我尝试过的
Simply calling ParentControl.ShowAlert()
where I've wrote the comment - obviously doesn't work as parentControl
is the instance (I don't want to refer to this explicitly). 简单地在我写评论的地方调用
ParentControl.ShowAlert()
-显然不起作用,因为parentControl
是实例(我不想明确地引用它)。
I've also tried passing in the parent control to the constructor of ChildControl
but I ideally wanted to keep the child control independent from any particular type of parent. 我也尝试过将父控件传递给
ChildControl
的构造函数,但理想情况下,我希望保持子控件独立于任何特定类型的父控件。
I'd also move showAlert onto the prototype, so you're not creating a new function in memory every time you instantiate ParentControl. 我还将showAlert移到原型上,这样就不必在每次实例化ParentControl时在内存中创建一个新函数。
var ParentControl = function() {
this.childControl = new ChildControl(this);
};
ParentControl.prototype.showAlert = function() {
console.log('hello');
};
var ChildControl = function(parent) {
parent.showAlert();
};
var parentControl = new ParentControl();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.