Ilya Gazman
Ilya Gazman

Reputation: 32241

Javascript call parent function

Question inside the description

function Parent(){
    this.alertParent(){
        alert("Parent alert");
    }

    function child(){
        // how can I call to this.alertParent() from here without passing any  
        // parameters?
    }
}

Upvotes: 3

Views: 16992

Answers (2)

Felix Kling
Felix Kling

Reputation: 816590

The title of your question is confusing. The informal term "parent" function is rather used for the calling function.

In your case, you have two functions inside a constructor function and you just want to call one from the other. Specifically, you want to call a "public" method from a "private" method (I put these terms in quotes since JavaScript does not support visibility and these are workaround to achieve the same).

Just keep a reference to the current instance:

function Parent(){
    var self = this;
    this.alertParent = function() {
        alert("Parent alert");
    }

    function child() {
        self.alertParent();
    }
}

child closes over all variables in the context it is defined, so it as access to self. this of course changes [MDN].

Instead of creating a closure, you can also pass the instance explicitly to child, using either .call() [MDN] or .apply() [MDN].

So your function definition stays

function child() {
    this.alertParent();
}

and when you call the function, you call it, e.g. with child.call(this) if you know that this refers to your instance (instead of this it can be any other variable).

Upvotes: 12

xdazz
xdazz

Reputation: 160863

Your code has syntax error. Maybe you means this:

function Parent(){
    this.alertParent = function () {
        alert("Parent alert");
    };

    this.child = function () {
      this.alertParent();
    }
}

Upvotes: 3

Related Questions