Can you write nested functions in JavaScript?

前端 未结 5 1063
不知归路
不知归路 2020-11-28 20:47

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 t

5条回答
  •  盖世英雄少女心
    2020-11-28 21:19

    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:

       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.

提交回复
热议问题