如何在ES6中引用未命名的析构参数?

时间:2016-08-04 17:57:41

标签: javascript ecmascript-6

在下面的代码中,我想知道是否有一些东西要替换 magic ,它会像在foo上面调用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;
}

1 个答案:

答案 0 :(得分:1)

在函数内执行destructure。像这样:

function bar(obj) {
  const { b = 2, c = 3 } = obj
  const magic = { b, c }
  foo(99, magic); // abracadabra
}
相关问题