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

前端 未结 4 1967
我寻月下人不归
我寻月下人不归 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 05:03

    In order to use objects (or functions) as keys you'll need to use Harmony (EcmaScript 6) WeakMap or Map. They're both currently experimental and both are available in Firefox. I believe WeakMap might also be available in Chrome (with the proper flag settings?).

    If your platform supports WeakMap, and you choose to incorporate them, then their usage is quite straightforward:

    var myWeakMap=new WeakMap();
    myWeakMap.get(key [, defaultValue]);
    myWeakMap.set(key, value);
    myWeakMap.has(key);
    myWeakMap.delete(key);
    myWeakMap.clear();
    

    More information (note the MDN references appear to be unlisted):

    • https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/WeakMap
    • https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Map
    • http://wiki.ecmascript.org/doku.php?id=harmony:weak_maps

    Also: Alternatively you can use an array of functions, then use indexOf to get the index of the function, then access the parameters in an another array with that index.

    function a(){}
    function b(){}
    var x=[a,b].indexOf(b);  //x=1
    

提交回复
热议问题