我正在使用node.js v4.3.1
我想在调用函数时使用命名参数,因为它们更易读。
在Python中,我可以这样调用一个函数;
info(spacing=15, width=46)
我该如何在node.js中实现同样的功能?
我的JavaScript函数大致如下;
function info(spacing, width)
{
//implementation
{
我正在使用node.js v4.3.1
我想在调用函数时使用命名参数,因为它们更易读。
在Python中,我可以这样调用一个函数;
info(spacing=15, width=46)
我该如何在node.js中实现同样的功能?
我的JavaScript函数大致如下;
function info(spacing, width)
{
//implementation
{
标准的JavaScript方式是传递一个名为“options”的对象,例如:
info({spacing:15, width:46});
在代码中使用
function info(options) {
var spacing = options.spacing || 0;
var width = options.width || "50%";
...
}
在 JavaScript 中,如果对象缺少属性键,则返回 undefined
,它是“假值”。
请注意,在这种代码中传递“假值”的值可能会导致问题... 因此,如果需要,请编写更复杂的代码,如:
var width = options.hasOwnProperty("width") ? options.width : "50%";
或者var width = "width" in options ? options.width : "50%";
根据您是否想要支持继承选项来确定。
还要注意,JavaScript中的每个“标准”对象都会继承一个constructor
属性,因此不要以这种方式命名选项。
||
的东西?它们是默认值吗?我理解的对吗? - guagay_wkwidth
,则options.width
将返回undefined
,因此||
运算符将选择右侧。 - 6502options.hasOwnProperty
و›´ه®‰ه…¨هگ—ï¼ں"falsy"وک¯ن»€ن¹ˆو„ڈو€ï¼ں - guagay_wk||
之前的内容评估为false,则将使用右侧的部分。 - Sverri M. Olsen在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 })
顺序不重要。
{ param:value }
)来传递参数。 - Sverri M. Olsen