1
在下面的代码中,我想知道是否有什么东西可以取代魔术,它可以完成与foo上面的调用相同的功能。如何引用ES6中未命名的解构参数?
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});
原因是我有一个函数,其中未命名的对象参数是相当大的,这似乎是一个速记看起来更好,更少错误不是每次写所有的对象键容易。 (我移植从蟒蛇ES6库,并试图保持现有的API尽可能多的可能。)
编辑:另一种方式来问这个是:“有没有办法来遍历这些参数b和c不知道他们的名字?“
编辑2:这里是真实的代码。功能性但丑陋。必须是更好的方法。
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;
}