What is the most efficient way to create map of functions to arguments?

前端 未结 4 1970
我寻月下人不归
我寻月下人不归 2021-01-07 04:32

I want to create a map of functions to its argument. This map will be updated dynamically. Finally all the functions will be called with their corresponding arguments.

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-07 04:52

    Objects in JavaScript can only have strings as keys, so using map[foo1] is practically identical to map[foo1.toString()]. These both have problems that you haven't noticed: they discard closed-over variables, e.g.:

    function makeCounter() {
        var counter = 0;
        return function() { return ++counter; }
    }
    

    If I have

    var myCounter = makeCounter();
    

    then myCounter.toString() will be function() { return ++counter; }, and trying to reconstitute that with the Function constructor will result in having the wrong counter reference.

    Really, the best option might be to use the function's name as the property and as a value, use an object like you suggested:

    var map = {};
    map['foo1'] = { fn: foo1, args: [1, 2, 3] };
    

    Then, if you want to add more arguments later, it's pretty obvious:

    map['foo1'].args.push(4);
    

    And to call them all, you might use something like this:

    for(var functionName in map) {
        if(!Object.prototype.hasOwnProperty.call(map, functionName)) {
            continue;
        }
        map[functionName].fn.apply(null, map[functionName].args);
    }
    

提交回复
热议问题