在下面的代码中,我想知道是否有东西可以替代 magic ,它会执行与上面对 foo 的调用相同的操作。
function foo(a, { b=0, c=1 } = {} ) {
console.log(a, b, c);
}
function bar({ b=2, c=3 } = {} ) {
foo(99, { b:b, c:c });
// foo(99, magic); // should be equivalent to the above call
}
bar({c:4});
原因是我有一个函数,其中未命名的对象参数非常大,而且与每次都写入所有对象键相比,速记看起来更好并且更不容易出错。 (我正在将一个库从 python 移植到 ES6,并尝试尽可能维护现有的 api。)
<小时/>编辑:问这个问题的另一种方式是:“有没有办法在不知道参数名称的情况下循环遍历这些参数 b 和 c?”
<小时/>Edit2:这是真实的代码。实用但丑陋。一定是更好的方法。
function Decoder({
encoding="utf-8",
object_hook=echo,
parse_float=Number,
parse_int=Number,
parse_constant=Number,
strict=true,
object_pairs_hook=echo} = {}) {
if(!(this instanceof Decoder)) {
return new Decoder({
encoding:encoding,
object_hook:object_hook,
parse_float:parse_float,
parse_int:parse_int,
parse_constant:parse_constant,
strict:strict,
object_pairs_hook:object_pairs_hook});
}
this.encoding = encoding;
this.object_hook = object_hook;
this.parse_float = parse_float;
this.parse_int = parse_int;
this.parse_constant = parse_constant;
this.strict = strict;
this.object_pairs_hook = object_pairs_hook;
}
最佳答案
在函数内部执行解构。像这样的事情:
function bar(obj) {
const { b = 2, c = 3 } = obj
const magic = { b, c }
foo(99, magic); // abracadabra
}
关于javascript - 如何在ES6中引用未命名的解构参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38774309/