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?
}
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
childcloses over all variables in the context it is defined, so it as access toself.thisof 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
and when you call the function, you call it, e.g. with
child.call(this)if you know thatthisrefers to your instance (instead ofthisit can be any other variable).