在node.js中使用命名参数

use*_*486 10 javascript function named-parameters node.js

我正在使用node.js v4.3.1

我想在调用函数时使用命名参数,因为它们更具可读性.

在python中,我可以用这种方式调用函数;

info(spacing=15, width=46)
Run Code Online (Sandbox Code Playgroud)

我如何在node.js中做同样的事情?

我的javascript函数看起来像这样;

function info(spacing, width)
{
   //implementation
{
Run Code Online (Sandbox Code Playgroud)

650*_*502 12

标准的Javascript方式是传递一个"选项"对象

info({spacing:15, width:46});
Run Code Online (Sandbox Code Playgroud)

在代码中使用

function info(options) {
    var spacing = options.spacing || 0;
    var width = options.width || "50%";
    ...
}
Run Code Online (Sandbox Code Playgroud)

因为对象中缺少的键返回undefined"falsy".

请注意,使用这种代码传递"falsy"值可能会有问题...所以如果需要这样,你必须编写更复杂的代码,如

var width = options.hasOwnProperty("width") ? options.width : "50%";
Run Code Online (Sandbox Code Playgroud)

要么

var width = "width" in options ? options.width : "50%";
Run Code Online (Sandbox Code Playgroud)

取决于您是否要支持继承选项.

还要注意Javascript中的每个"标准"对象都继承了一个constructor属性,因此不要以这种方式命名选项.


Utk*_*unç 10

ES6更容易.nodejs> 6.5支持这些功能.

你应该看看这个链接:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

您要使用的确切用法已实现.但是我不推荐它.

下面的代码(取自上面的链接)是一种更好的做法,因为您不必记住应该以何种顺序编写参数.

function drawES6Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
console.log(size, cords, radius);
 // do some chart drawing
}
Run Code Online (Sandbox Code Playgroud)

你可以通过这样做来使用这个功能:

const cords = { x: 5, y: 30 }
drawES6Chart({ size: 'small', cords: cords })
Run Code Online (Sandbox Code Playgroud)

这样,函数变得更容易理解,如果你有名为size,cords和radius的变量,它会变得更好.然后你可以使用对象速记来做到这一点.

// define vars here
drawES6Chart({ cords, size, radius })
Run Code Online (Sandbox Code Playgroud)

订单没关系.