javascript Javascript调用父函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10960162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript call parent function
提问by Ilya Gazman
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?
}
}
回答by Felix Kling
The title of your question is confusing. The informal term "parent" function is rather used for the callingfunction.
你的问题标题令人困惑。非正式术语“父”函数用于调用函数。
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).
在您的情况下,您在构造函数中有两个函数,而您只想从另一个调用一个。具体来说,您希望从“私有”方法调用“公共”方法(我将这些术语放在引号中,因为 JavaScript 不支持可见性,而这些是实现相同目的的变通方法)。
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].
child
关闭它定义的上下文中的所有变量,因此它可以访问self
. this
当然改变[MDN]。
Instead of creating a closure, you can also pass the instance explicitlyto child
, using either .call()
[MDN]or .apply()
[MDN].
除了创建闭包,您还可以使用[MDN]或[MDN]将实例显式传递给。child
.call()
.apply()
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).
并且当您调用该函数时,您会调用它,例如,child.call(this)
如果您知道它this
指的是您的实例(而不是this
它可以是任何其他变量)。
回答by xdazz
Your code has syntax error. Maybe you means this:
您的代码有语法错误。也许你的意思是:
function Parent(){
this.alertParent = function () {
alert("Parent alert");
};
this.child = function () {
this.alertParent();
}
}