Can you write nested functions in JavaScript?

前端 未结 5 1029
不知归路
不知归路 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:00

    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();
    
    0 讨论(0)
  • 2020-11-28 21:15

    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));

    0 讨论(0)
  • 2020-11-28 21:15

    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 21:19

    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(){
    
       }
    }
    
    0 讨论(0)
提交回复
热议问题