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

前端 未结 10 1713
抹茶落季
抹茶落季 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:41

    Calling function f with named parameters passed as the object

    o = {height: 1, width: 5, ...}
    

    is basically calling its composition f(...g(o)) where I am using the spread syntax and g is a "binding" map connecting the object values with their parameter positions.

    The binding map is precisely the missing ingredient, that can be represented by the array of its keys:

    // map 'height' to the first and 'width' to the second param
    binding = ['height', 'width']
    
    // take binding and arg object and return aray of args
    withNamed = (bnd, o) => bnd.map(param => o[param])
    
    // call f with named args via binding
    f(...withNamed(binding, {hight: 1, width: 5}))
    

    Note the three decoupled ingredients: the function, the object with named arguments and the binding. This decoupling allows for a lot of flexibility to use this construct, where the binding can be arbitrarily customized in function's definition and arbitrarily extended at the function call time.

    For instance, you may want to abbreviate height and width as h and w inside your function's definition, to make it shorter and cleaner, while you still want to call it with full names for clarity:

    // use short params
    f = (h, w) => ...
    
    // modify f to be called with named args
    ff = o => f(...withNamed(['height', 'width'], o))
    
    // now call with real more descriptive names
    ff({height: 1, width: 5})
    

    This flexibility is also more useful for functional programming, where functions can be arbitrarily transformed with their original param names getting lost.

提交回复
热议问题