簡體   English   中英

我如何從孩子那里指代父母?

[英]How can I refer to a parent from a child?

標題的措詞可能需要重新訪問,但現在考慮以下代碼:

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移到原型上,這樣就不必在每次實例化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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM