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;
}