简体   繁体   English

在函数 JavaScript 中使用函数

[英]Use a function within a function JavaScript

I have kept below simply for context:我只是为了上下文而保留在下面:


How could I make a function inside a function (without nesting or using variables)?如何在函数内部创建函数(不嵌套或使用变量)?

Example of what I want:我想要的例子:

var openPage = 1
function pageGame()
{

}
function pageUpgrades()
{
    openPage = 2;
    do checkPage()
}
function pageStats()
{

}
function checkPage()
{
    if (openPage ==     1)
    {
        document.getElementById("game").className = "open";
        document.getElementById("upgrades").className = "";
        document.getElementById("stats").className = "";            
    }
    if (openPage ==     2)
    {
        document.getElementById("game").className = "";
        document.getElementById("upgrades").className = "open";
        document.getElementById("stats").className = "";    
    }
    if (openPage ==     3)
    {
        document.getElementById("game").className = "";
        document.getElementById("upgrades").className = "";
        document.getElementById("stats").className = "open";    
    }
}

I want the function "checkPage" to run when I tell it to in "pageUpgrades"当我在“pageUpgrades”中告诉它时,我希望函数“checkPage”运行

Sorry if this is a duplicate, I couldn't find any answers anywhere.抱歉,如果这是重复的,我在任何地方都找不到任何答案。

Edit - Note: I did attempt to use a simple checkPage() (without the do)编辑 - 注意:我确实尝试使用一个简单的checkPage() (没有做)


Edit 3.5 years later: Wow, I certainly regret this post. 3.5 年后编辑:哇,我当然后悔这篇文章。

Please do note, for future viewers, if you ever want to to run a function within a function in JavaScript, simply specify the function within your code.请注意,对于未来的查看者,如果您想在 JavaScript 中的函数中运行函数,只需在代码中指定该函数即可。 Functions are accessible from anywhere so once specified you can execute your function simply by calling it.函数可以从任何地方访问,因此一旦指定,您只需调用它即可执行您的函数。

If your function has parameters, specify those else you simply need: function()如果您的函数有参数,请指定您只需要的其他参数: function()

It is good practice to use semicolons even when unnecessary, see the comments below this post for the confusion there.即使在不必要的情况下也使用分号是一种很好的做法,请参阅这篇文章下面的评论以了解那里的混乱。

我不知道为什么在函数调用之前有do关键字,但除此之外,您已经从pageUpgrades调用checkPage函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM