解释一下这个函数参数中的{target = document.body} = {}

Explain {target = document.body} = {} in this function parameter

谁能帮我理解下面的函数 {target = document.body} = {} 是怎么回事?

好像是传递一个默认为空对象的对象作为参数?但是 target = document.body 似乎不是有效的对象语法。

const replaceOnDocument = (pattern, string, {target = document.body} = {}) => {

  // Handle `string` — see the last section
  [
    target,
    ...target.querySelectorAll("*:not(script):not(noscript):not(style)")
  ].forEach(({childNodes: [...nodes]}) => nodes
    .filter(({nodeType}) => nodeType === document.TEXT_NODE)
    .forEach((textNode) => textNode.textContent = textNode.textContent.replace(pattern, string)));
};

在函数的参数列表中,{target = document.body} = {}表示:

  • 它的{target}部分是参数解构。它的意思是“将提供的对象的 target 属性 作为参数放入参数 target 中。”这称为解构参数
  • = document.body 部分是 解构默认值 。意思是如果对象上没有target属性(或者它的值为undefined),target应该得到值document.body.
  • 解构关闭}后的= {}参数默认值。这意味着如果该参数根本没有参数(或者参数是 undefined),则使用 {} 作为参数的默认值。之后,解构应用于该参数默认值。 (在下面的示例中有更多相关内容,可能有点令人困惑。)

结果是 target 将是作为参数提供的对象的 target 属性(如果提供而不是 undefined),或者 document.body.

例如,如果您调用 replaceOnDocument 时根本没有第三个参数,则会触发默认参数值 ({});然后解构将看不到 target 属性,因此将使用解构默认值 (document.body)。

这是一个例子:

function example({target = "a"} = {}) {
    console.log(`target = ${target}`);
}

// Calling with no argument at all triggers the default parameter
// value (`{}`), which in turn triggers the default destructuring
// value since `{}` doesn't have `target`.
example(); // "target = a"

// Calling with an object that doesn't have `target` just triggers the
// default destructuring value
example({randomProperty: 42}); // "target = a"

// But calling with an object that has `target`, the `target` from
// the object gets picked up
example({target: "b"}); // "target = b"

// Let's see a different value for the default parameter value:
function example2({target = "1"} = {target: "2"}) {
    console.log(`target = ${target}`);
}

// Calling with no argument at all triggers the default parameter
// value (`{}`), which in turn triggers the default destructuring
// value since `{}` doesn't have `target`.
example2(); // "target = 2"

// Calling with an object that doesn't have `target` just triggers the
// default destructuring value
example2({randomProperty: 42}); // "target = 1"

// Calling with an object that has `target`, the `target` from
// the object gets picked up
example2({target: "3"}); // "target = 3"