如何在一个函数中调用另一个函数?

72

我想知道如何在另一个函数中调用JavaScript函数。如果我有以下代码,如何在第一个函数中调用第二个函数?

function function_one()
{
alert("The function called 'function_one' has been called.")
//Here I would like to call function_two.
}

function function_two()
{
alert("The function called 'function_two' has been called.")
}
4个回答

118

function function_one() {
    function_two(); // considering the next alert, I figured you wanted to call function_two first
    alert("The function called 'function_one' has been called.");
}

function function_two() {
    alert("The function called 'function_two' has been called.");
}

function_one();

稍微提供一些背景信息:这在JavaScript中有效,因为有一种语言特性叫做“变量提升” - 基本上,可以将其视为变量/函数声明放在作用域的顶部 (更多信息)。

如果function_one是一个可调用函数,该怎么办。例如以下变异示例的情况。https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver如何从可调用函数内部调用function_two - Sizzling Code
1
@SizzlingCode 我不确定这与我上面的代码有什么不同。这段代码之所以有效,是因为存在“变量提升”:https://scotch.io/tutorials/understanding-hoisting-in-javascript - Christian

23
function function_one() {
  function_two(); 
}

function function_two() {
//enter code here
}

5

function function_one()
{
    alert("The function called 'function_one' has been called.")
    //Here u would like to call function_two.
    function_two(); 
}

function function_two()
{
    alert("The function called 'function_two' has been called.")
}


0
function function_first() {
    function_last(); 
    alert("The function called 'function_first' has been called.");
}

function function_last() {
    alert("The function called 'function_last' has been called.");
}

function_first();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接