在Javascript中调用另一个函数内定义的函数 [英] Calling a Function defined inside another function in Javascript

查看:1095
本文介绍了在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.

推荐答案

正如您所指出的那样,范围是正确的。但是,你没有在任何地方调用内部函数。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆