[英]ES6 Named Object Parameter Destructuring
I am currently using the object destructuring pattern with default parameters described in that answer to ES6 Object Destructuring Default Parameters . 我目前正在使用对象解构模式和ES6对象解析默认参数的答案中描述的默认参数 。
(function test({a = "foo", b = "bar"} = {}) {
console.log(a + " " + b);
})();
I would like to be able to access the object parameter without assigning it to a variable in the function body and explicitly listing each key. 我希望能够访问object参数,而无需将其分配给函数体中的变量并显式列出每个键。
(function test({a = "foo", b = "bar"} = {}) { const options = {a, b}; console.log(options); })();
I tried naming the object argument, but the function looses the ability to resolve missing keys to their default value. 我尝试命名对象参数,但该函数失去了将缺失键解析为其默认值的能力。
(function test(options = {a = "foo", b = "bar"} = {}) { console.log(options); })();
It seems to be ignoring the default parameters when destructuring into a named argument. 在解构为命名参数时,它似乎忽略了默认参数。
Is this part of the ES6 spec? 这是ES6规范的一部分吗? Is there a way to achieve the desired behavior without additional code in the function body?
有没有办法在函数体中没有附加代码的情况下实现所需的行为?
Edit: I removed a superfluous example that did not add context to the question. 编辑:我删除了一个没有为问题添加上下文的多余示例。
Honestly, I think you're overcomplicating this. 老实说,我认为你过于复杂了。 Default parameters are not compulsory -- in this case your code can be cleaner without it.
默认参数不是强制性的 - 在这种情况下,如果没有它,您的代码可以更清晰。
I would simply take the object options
as the parameter and do the destructuring within the body of the function, after assigning default values. 在分配默认值之后,我只需将对象
options
作为参数并在函数体内进行解构。
function test(options) { options = Object.assign({a: 'foo', b: 'bar'}, options); let {a, b} = options; console.log(options, a, b); } test(); // foo bar test({a: 'baz'}); // baz bar test({b: 'fuz'}); // foo fuz test({c: 'fiz'}); // foo bar
With particular regard to your final snippet: 特别关注你的最终片段:
(function test(options = {a: "foo", b: "bar"}) { console.log(options); })({a: "baz"});
The problem is that a default parameter is used when the value passed is undefined
. 问题是当传递的值
undefined
时使用默认参数。 Here, the value passed is {a: "baz"}
. 这里传递的值是
{a: "baz"}
。 That is not undefined
, so the default parameter is ignored. 这不是
undefined
,因此忽略默认参数。 Objects are not merged automatically. 对象不会自动合并。
More broadly in answer to your question: there is no way of getting both an object and destructuring some of its properties in the parameters of a method. 更广泛地回答您的问题:无法同时获取对象并在方法的参数中解构其某些属性。 Frankly, I'm grateful, because function signatures can be hard enough to read at first glance as it is.
坦率地说,我很感激,因为功能签名很难以乍看之下阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.