此 JS 函数参数语法(具有 属性 默认值的对象初始值设定项,类似于 rest/spread 参数)是否有名称和效果?

Does this JS function param syntax (object initializer with property defaults, similar to rest/spread params) have a name and effect?

我正在阅读我以前从未见过的 logging library source code when I found syntax,并且在通过解释器评估时似乎没有任何效果:

const createLogger = (title,
                     {
                         debugFunction = createDebug(title),
                         logFunction = console.log
                     } = {}) => { /* ... */ }
  1. 这个语法叫什么?
  2. 这个语法有什么作用?
  3. 可以从函数体内引用对象吗?

ts-node 尝试重新创建的输出:

> const testFn2 = (arg1, {dFn = console.debug, lFn = console.log} = {}) => { console.log(arguments) }
undefined

> testFn2(1)
{ '0': 1 }
undefined

> testFn2(1, 2)
{ '0': 1, '1': 2 }
undefined

> testFn2(1, {})
{ '0': 1, '1': {} }
undefined

它是

的组合

以及

...都是在ES2015中添加的

它创建一个常量 createLogger,并将其值设置为名为 createLogger 的函数,该函数接受两个参数:标题 (title) 和 object. object 解构debugFunctionlogFunction 参数,如果不存在则默认为 {}

这是一个更简单的解构参数示例:

function foo({a, b}) {
// Note -----^----^
  console.log(a, ",", b);
}

const o = {a: 1, b: 2};
foo(o); // 1 , 2

请注意我们如何使用 object 调用 foo,但是 foo 的代码使用两个参数,其值是 解构的 来自 object 的属性。

如果我们不带参数调用 foo,我们会得到一个错误,因为解构试图访问参数的属性,而访问 undefined 的属性失败:

function foo({a, b}) {
  console.log(a, ",", b);
}

foo(); // Fails

如果我们为参数添加一个默认值,它会起作用:

function foo({a, b} = {a: "default a"}) {
// ----------------^^^^^^^^^^^^^^^^^^^
  console.log(a, ",", b);
}

foo(); // default a , undefined (since there's no `b` in the default)

它被称为参数解构加上默认值:

let default1 = 1;
let default2 = 2;

const func = ({a = default1, b = default2} = {}) => {
  console.log(a);
  console.log(b);
}

// Here since no value is specified, the default argument will be {a: 1, b: 2}
func();

您正在查看一个 object destructring assignment,在本例中用于初始化局部变量并为其分配默认值,而无需在函数体中声明它们。这是一种避免编写额外代码的模式;如果你没有破坏性语法,你基本上会写:

const createLogger = (name, params = {}) => {
    let debugFunction = params.debugFunction || createDebug(name);
    let logFunction = params.logFunction || console.log;

     // do stuff
}

在这一点上,它可能会产生更多的问题,而不是它消除的少量代码所值得的;清晰胜于简洁,尤其是在大型项目中。您 可以 组合多个三元赋值而不是编写 if-else 块,但那样读起来会很糟糕。另一方面,这种风格可能会更流行。