Can you write nested functions in JavaScript?

前端 未结 5 1048
不知归路
不知归路 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();
    

提交回复
热议问题