【问题标题】:Using named parameters in node.js在 node.js 中使用命名参数
【发布时间】:2016-06-11 08:35:16
【问题描述】:

我正在使用 node.js v4.3.1

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

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

info(spacing=15, width=46)

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

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

function info(spacing, width)
{
   //implementation
{

【问题讨论】:

  • Javascript 没有命名函数参数。传递对象字面量 ({ param:value }) 通常是在 Javascript 中完成的。

标签: javascript node.js function named-parameters


【解决方案1】:

标准的 Javascript 方法是传递一个“选项”对象,如

info({spacing:15, width:46});

在代码中使用

function info(options) {
    var spacing = options.spacing || 0;
    var width = options.width || "50%";
    ...
}

因为对象中缺少的键返回undefined,即“虚假”。

请注意,使用这种代码传递“虚假”的值可能会出现问题...因此,如果需要,您必须编写更复杂的代码,例如

var width = options.hasOwnProperty("width") ? options.width : "50%";

var width = "width" in options ? options.width : "50%";

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

还要注意,Javascript 中的每个“标准”对象都继承了 constructor 属性,所以不要这样命名选项。

【讨论】:

  • 你为什么要添加那些|| 的东西?它们是默认值吗?我说的对吗?
  • @user1824987: 是的...如果width 未通过options.width 将返回undefined,因此|| 运算符将选择右侧。
  • 始终使用options.hasOwnProperty 是否更安全? “虚假”是什么意思?
  • @user1824987 它的工作方式很像其他语言中的null-coalescing operators。如果|| 之前的内容评估为false,则将使用右侧的部分。
【解决方案2】:

使用 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
}

您可以通过以下方式使用此功能:

const cords = { x: 5, y: 30 }
drawES6Chart({ size: 'small', cords: cords })

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

// define vars here
drawES6Chart({ cords, size, radius })

顺序无关紧要。

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 2020-10-08
    • 2015-07-29
    • 2016-08-22
    • 1970-01-01
    • 2011-03-09
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多