描述中的问题
function Parent(){
this.alertParent(){
alert("Parent alert");
}
function child(){
// how can I call to this.alertParent() from here without passing any
// parameters?
}
}
最佳答案
您的问题标题令人困惑。非正式术语“父”函数更适用于调用 函数。
在您的情况下,构造函数中有两个函数,您只想从另一个调用一个。具体来说,您想从“私有(private)”方法调用“公共(public)”方法(我将这些术语放在引号中,因为 JavaScript 不支持可见性,这些是实现相同目的的解决方法)。
只保留对当前实例的引用:
function Parent(){
var self = this;
this.alertParent = function() {
alert("Parent alert");
}
function child() {
self.alertParent();
}
}
child
关闭它定义的上下文中的所有变量,因此它作为对 self
的访问。 this
of course changes [MDN] .
除了创建闭包之外,您还可以使用 .call()
[MDN] 将实例显式 传递给child
。或 .apply()
[MDN] .
所以你的函数定义保留
function child() {
this.alertParent();
}
当你调用函数时,你调用它,例如使用 child.call(this)
如果您知道 this
引用您的实例(而不是 this
它可以是任何其他变量)。
关于Javascript 调用父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10960162/