你能用 JavaScript 编写嵌套函数吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3212477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:41:37  来源:igfitidea点击:

Can you write nested functions in JavaScript?

javascriptfunctionnested

提问by Red Swan

I am wondering if JavaScript supports writing a function within another function, or nested functions (I read it in a blog). Is this really possible?. In fact, I have used these but am unsure of this concept. I am really unclear on this -- please help!

我想知道 JavaScript 是否支持在另一个函数或嵌套函数中编写函数(我在博客中读到它)。这真的可能吗?。事实上,我已经使用过这些,但我不确定这个概念。我对此真的不清楚 - 请帮忙!

回答by kennytm

Is this really possible.

这真的可能吗。

Yes.

是的。

function a(x) {    // <-- function
  function b(y) { // <-- inner function
    return x + y; // <-- use variables from outer scope
  }
  return b;       // <-- you can even return a function.
}
console.log(a(3)(4));

回答by Quentin

The following is nasty, but serves to demonstrate how you can treat functions like any other kind of object.

以下内容令人讨厌,但用于演示如何像对待任何其他类型的对象一样对待函数。

var foo = function () { alert('default function'); }

function pickAFunction(a_or_b) {
    var funcs = {
        a: function () {
            alert('a');
        },
        b: function () {
            alert('b');
        }
    };
    foo = funcs[a_or_b];
}

foo();
pickAFunction('a');
foo();
pickAFunction('b');
foo();

回答by cgp

Functions are first class objects that can be:

函数是第一类对象,可以是:

  • Defined within your function
  • Created just like any other variable or object at any point in your function
  • Returned from your function (which may seem obvious after the two above, but still)
  • 在您的函数中定义
  • 就像在函数中的任何点创建的任何其他变量或对象一样
  • 从您的函数返回(在上述两个之后似乎很明显,但仍然如此)

To build on the example given by Kenny:

以 Kenny 给出的示例为基础:

   function a(x) {
      var w = function b(y) {
        return x + y;
      }
      return w;
   };

   var returnedFunction = a(3);
   alert(returnedFunction(2));

Would alert you with 5.

会用 5 来提醒你。

回答by user3261767

Yes, it is possible to write and call a function nested in another function.

是的,可以编写和调用嵌套在另一个函数中的函数。

Try this:

尝试这个:

function A(){
   B(); //call should be B();
   function B(){

   }
}

回答by Stefan Gruenwald

Not only can you return a function which you have passed into another function as a variable, you can also use it for calculation inside but defining it outside. See this example:

您不仅可以返回作为变量传递给另一个函数的函数,还可以将其用于内部计算但在外部定义它。看这个例子:

    function calculate(a,b,fn) {
      var c = a * 3 + b + fn(a,b);
      return  c;
    }

    function sum(a,b) {
      return a+b;
    }

    function product(a,b) {
      return a*b;
    }

    document.write(calculate (10,20,sum)); //80
    document.write(calculate (10,20,product)); //250