javascript - 如何在ES6中引用未命名的解构参数?

标签 javascript ecmascript-6

在下面的代码中,我想知道是否有东西可以替代 ma​​gic ,它会执行与上面对 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。)

<小时/>

编辑:问这个问题的另一种方式是:“有没有办法在不知道参数名称的情况下循环遍历这些参数 bc?”

<小时/>

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/

相关文章:

javascript - 如何通过 RequireJS 在 AMD 模块中使用 javascript 对象

javascript - 如何在 HTML5 中创建 "Pie Chart"?

javascript - 将元素从附加列表传递到另一个页面

javascript - 使用 ES6 模块的 CreateJS

javascript - 您可以在 ES 中指定一个没有 catch 或 finally block 的 try 处理程序吗?

javascript - 单击的元素函数参数的值是错误的

javascript - 如何在IE8中动态创建CSS类

javascript - 深度赋值 JavaScript 对象字面量

javascript - React 中的表单行为不符合预期

javascript - Vue.js:观察数组长度