gpt4 book ai didi

javascript - 我如何从 child 中提及 parent ?

转载 作者:行者123 更新时间:2023-12-03 12:27:07 26 4
gpt4 key购买 nike

标题的措辞可能需要重新审视,但现在考虑以下代码:

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();

根据上面代码片段中的注释,我需要 ChildControl 实例来调用其父级的“ShowAlert”函数,但我不知道如何操作。

我尝试过的

只需在我写评论的地方调用 ParentControl.ShowAlert() - 显然不起作用,因为 parentControl 是实例(我不想引用明确这一点)。

我还尝试将父控件传递给 ChildControl 的构造函数,但理想情况下我希望保持子控件独立于任何特定类型的父控件。

最佳答案

我还将 showAlert 移至原型(prototype)上,这样每次实例化 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();

关于javascript - 我如何从 child 中提及 parent ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24144672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com