user1017882
user1017882

Reputation:

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.

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).

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.

Upvotes: 0

Views: 52

Answers (1)

Alexis Abril
Alexis Abril

Reputation: 6459

I'd also move showAlert onto the prototype, so you're not creating a new function in memory every time you instantiate 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();

Upvotes: 1

Related Questions