我发现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
}

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

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


当前回答

另一种方法是使用一个合适对象的属性,例如:

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);

当然,对于这个虚构的例子来说,它是没有意义的。但在函数看起来像这样的情况下

do_something(some_connection_handle, some_context_parameter, some_value)

它可能更有用。它还可以与“parameterfy”思想相结合,以通用的方式从现有函数中创建这样一个对象。也就是说,它将为每个形参创建一个成员,该成员可以求值为函数的部分求值版本。

这个想法当然与Schönfinkeling也就是curiling有关。

其他回答

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

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

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

警告:

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

另一种方法是使用一个合适对象的属性,例如:

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);

当然,对于这个虚构的例子来说,它是没有意义的。但在函数看起来像这样的情况下

do_something(some_connection_handle, some_context_parameter, some_value)

它可能更有用。它还可以与“parameterfy”思想相结合,以通用的方式从现有函数中创建这样一个对象。也就是说,它将为每个形参创建一个成员,该成员可以求值为函数的部分求值版本。

这个想法当然与Schönfinkeling也就是curiling有关。

很多人说使用“传递对象”技巧,这样你就有了命名参数。

/**
 * My Function
 *
 * @param {Object} arg1 Named arguments
 */
function myFunc(arg1) { }

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

这很有效,除了…当涉及到大多数IDE时,我们很多开发人员依赖于IDE中的类型/参数提示。我个人使用PhpStorm(以及其他JetBrains ide,如Python的PyCharm和Objective-C的AppCode)。

使用“传递对象”技巧的最大问题是,当你调用函数时,IDE会给你一个单一的类型提示,仅此而已……我们怎么知道什么参数和类型应该进入arg1对象?

所以…“传递一个对象”的把戏对我没用……实际上,在我知道函数需要什么参数....之前,不得不查看每个函数的文档块,这导致了更令人头痛的问题当然,这对于维护现有代码非常有用,但对于编写新代码则非常糟糕。

这就是我使用的技巧…现在,它可能会有一些问题,一些开发人员可能会告诉我我做错了,当涉及到这些事情时,我有一个开放的心态……我总是愿意寻找更好的方法来完成一项任务。因此,如果这种技术有问题,欢迎发表评论。

/**
 * My Function
 *
 * @param {string} arg1 Argument 1
 * @param {string} arg2 Argument 2
 */
function myFunc(arg1, arg2) { }

var arg1, arg2;
myFunc(arg1='Param1', arg2='Param2');

This way, I have the best of both worlds. New code is easy to write as my IDE gives me all the proper argument hints. And, while maintaining code later on, I can see at a glance, not only the value passed to the function, but also the name of the argument. The only overhead I see is declaring your argument names as local variables to keep from polluting the global namespace. Sure, it's a bit of extra typing, but it's trivial compared to the time it takes to look up docblocks while writing new code or maintaining existing code.

更新- 2022年

JavaScript现在可以在ES6中使用对象解构来实现类似于命名参数的功能。大多数较新的浏览器都可以使用此功能,请参阅浏览器支持

它是这样工作的:


// Define your function like this
function myFunc({arg1, arg2, arg3}) {
    // Function body
}

// Call your function like this
myFunc({arg1: "value1", arg2: "value2", arg3: "value3"})

// You can also have default values for arguments
function myFunc2({firstName, lastName, age = 21}) {
    // Function body
}

// And you can call it with or without an "age" argument
myFunc({firstName: "John", lastName: "Doe"}) // Age will be 21
myFunc({firstName: "Jane", lastName: "Doe", age: 22})

最好的部分是现在大多数IDE都支持这种语法,并且您可以获得良好的参数提示支持

打印稿

对于那些使用TypeScript的人,你可以使用这个语法做同样的事情

function myFunc(
    {firstName, lastName, age = 21}:
    {firstName: string, lastName: string, age?: number}
) {
    // Function body
}

或者,使用接口

interface Params {
    firstName: string
    lastName: string
    age?: number
}

function myFunc({firstName, lastName, age = 21}: Params) {
    // Function body
}

调用函数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})

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

如果你想弄清楚每个参数是什么,而不仅仅是调用

someFunction(70, 115);

做以下几点:

var width = 70, height = 115;
someFunction(width, height);

当然,这是额外的一行代码,但它在可读性上更胜一筹。