我发现c#中的命名参数特性在某些情况下非常有用。

calculateBMI(70, height: 175);

如果我想在JavaScript中使用这个,我可以使用什么?


我不想要的是:

myFunction({ param1: 70, param2: 175 });

function myFunction(params){
  // Check if params is an object
  // Check if the parameters I need are non-null
  // Blah blah
}

这个方法我已经用过了。还有别的办法吗?

我可以使用任何库来做到这一点。


当前回答

与通常认为的相反,命名参数可以在标准的旧式JavaScript中(仅用于布尔参数)通过简单、整洁的编码约定实现,如下所示。

function f(p1=true, p2=false) {
    ...
}

f(!!"p1"==false, !!"p2"==true); // call f(p1=false, p2=true)

警告:

必须保留参数的顺序——但这种模式仍然有用,因为它可以很明显地显示哪个实际参数对应哪个形式参数,而不必为函数签名进行grep或使用IDE。 这只适用于布尔值。但是,我相信可以使用JavaScript独特的类型强制语义为其他类型开发类似的模式。

其他回答

不——对象方法是JavaScript对此的答案。如果你的函数需要一个对象而不是单独的参数,这就没有问题。

NB。正如评论中提到的,我2016年的答案是不正确的,具有误导性。

尝试Node-6.4.0 (process.versions. Node-6.4.0)。v8 = '5.0.71.60')和Node Chakracore-v7.0.0-pre8,然后是Chrome-52 (v8 =5.2.361.49),我注意到命名参数几乎是实现的,但顺序仍然优先。我找不到ECMA标准是怎么说的。

>function f(a=1, b=2){ console.log(`a=${a} + b=${b} = ${a+b}`) }

> f()
a=1 + b=2 = 3
> f(a=5)
a=5 + b=2 = 7
> f(a=7, b=10)
a=7 + b=10 = 17

但是必须遵守秩序!!这是标准行为吗?

> f(b=10)
a=10 + b=2 = 12

调用函数f,将命名参数作为对象传递

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

基本上是调用它的组合f(…g(o)),其中我使用蔓延语法和g是一个“绑定”映射连接对象值及其参数位置。

绑定映射正是缺失的元素,可以用它的键数组表示:

// 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}))

请注意三个已解耦的成分:函数、带有命名参数的对象和绑定。这种解耦为使用此构造提供了很大的灵活性,其中绑定可以在函数的定义中任意定制,并在函数调用时任意扩展。

例如,在函数的定义中,你可能想要将高度和宽度缩写为h和w,使其更简短和清晰,同时你仍然想要使用全名来调用它:

// 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})

这种灵活性对于函数式编程也更有用,在函数式编程中,可以任意转换函数,而丢失其原始参数名。

这确实是伪代码,但我相信它会起作用(我知道它在TypeScript中起作用;我将它用于JavaScript)。

// Target Function
const myFunc = (a=1,b=2,c=3) => {a+b+c}

// Goal usage:
myFunc(a=5, b=6) // 14
myFunc(c=0) // 3

// Set your defaults
const myFuncDefaults = {a:1, b:2, c:3};

// Override them with passed parameters
const myFuncParams = (params) => { return Object.assign(myFuncDefaults, params)}


// Use the overloaded dict as the input
const myFunc2 = (params) => {
  let {a, b, c} = myFuncParams(params);
  return myFunc(a, b, c)
}

// Usage:
myFunc({a:5, b:6}) // 14
myFunc({c:0}) // 3

// Written more succinctly:
const myFunc = (params) => {
  let {a,b,c} = Object.assign({a:1, b:2, c:3}, params)
  return a + b + c
}

不管它的价值是什么,TypeScript通过提示来实现这一点:

interface IParams {
  a: number;
  b: number;
  c: number;
}

const myFunc = (params: Partial<IParams>): number => {
  const default: IParams = {a:1, b:2, c:3};
  let {a, b, c} = Object.assign(default, params)
  return a + b + c
}

来自Python,这让我很困扰。我为节点编写了一个简单的包装器/代理程序,它将接受位置对象和关键字对象。

https://github.com/vinces1979/node-def/blob/master/README.md