在 Javascript 中调用另一个函数中定义的函数 [英] Calling a Function defined inside another function in Javascript
本文介绍了在 Javascript 中调用另一个函数中定义的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在按钮点击时调用一个函数,如下所示:
I am calling a function on button click like this:
<input type="button" onclick="outer();" value="ACTION">
function outer() {
alert("hi");
}
它工作正常,我收到警报:
It works fine and I get an alert:
现在当我这样做时:
function outer() {
function inner() {
alert("hi");
}
}
为什么我没有收到警报?
Why don't I get an alert?
虽然内部函数在外部函数中有一个可用的作用域.
Though inner function has a scope available in outer function.
推荐答案
正如您所指出的,范围是正确的.但是,您不会在任何地方调用 inner
函数.
The scoping is correct as you've noted. However, you are not calling the inner
function anywhere.
你可以:
function outer() {
// when you define it this way, the inner function will be accessible only from
// inside the outer function
function inner() {
alert("hi");
}
inner(); // call it
}
或
function outer() {
this.inner = function() {
alert("hi");
}
}
<input type="button" onclick="(new outer()).inner();" value="ACTION">
这篇关于在 Javascript 中调用另一个函数中定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文