Is there a way to provide named parameters in a function call in JavaScript?

前端 未结 10 1731
抹茶落季
抹茶落季 2020-11-22 07:28

I find the named parameters feature in C# quite useful in some cases.

calculateBMI(70, height: 175);

What can I use if I want this in JavaS

10条回答
  •  一生所求
    2020-11-22 07:30

    Another way would be to use attributes of a suitable object, e.g. like so:

    function plus(a,b) { return a+b; };
    
    Plus = { a: function(x) { return { b: function(y) { return plus(x,y) }}}, 
             b: function(y) { return { a: function(x) { return plus(x,y) }}}};
    
    sum = Plus.a(3).b(5);
    

    Of course for this made up example it is somewhat meaningless. But in cases where the function looks like

    do_something(some_connection_handle, some_context_parameter, some_value)
    

    it might be more useful. It also could be combined with "parameterfy" idea to create such an object out of an existing function in a generic way. That is for each parameter it would create a member that can evaluate to a partial evaluated version of the function.

    This idea is of course related to Schönfinkeling aka Currying.

提交回复
热议问题