Can I store JavaScript functions in arrays?

前端 未结 9 2031
时光说笑
时光说笑 2021-01-30 05:34

How can I store functions in an array with named properties, so I can call like

FunctionArray["DoThis"]

or even

Function         


        
9条回答
  •  轮回少年
    2021-01-30 06:09

    The important thing to remember is that functions are first class objects in JavaScript. So you can pass them around as parameters, use them as object values and so on. Value(s) in an array are just one example of that.

    Note that we are not storing the functions in an array although we can do that and access them with a numeric index. We are storing them in a regular object keyed by the name we want to access that function with.

    var functions = {
        blah: function() { alert("blah"); },
        foo: function() { console.log("foo"); }
    };
    

    call as

    functions.blah();
    

    or

    functions["blah"]();
    

提交回复
热议问题