【问题标题】:JS ES6: Get parameters as an object with destructuringJS ES6:通过解构获取参数作为对象
【发布时间】:2016-11-09 16:16:52
【问题描述】:

是否可以使用解构将函数的参数作为对象获取(以便对其进行迭代)?

function({a=1, b=2, c=3}={}) {
  // how to get {a:1, b:2, c:3}?
}

我的目标是将每个参数绑定到类构造函数中的this

不用解构也是可能的:

class Test {
  constructor(args) {
    Object.assign(this, args);
  }
}

但我不知道如何简化:

class Test {
  constructor({a=1, b=2, c=3}={}) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
}

let test = new Test();
// test.a = 1 
// test.b = 2 etc.

【问题讨论】:

  • 所以你想让你的调用者用一个对象来调用这个函数?
  • 虽然我在下面为您发布了一个选项,但我只能说,this.a = a; 表单美观清晰,易于阅读,易于调试...
  • 我明白了。但是当有很多参数时,可能会有点不方便。

标签: javascript ecmascript-6 destructuring


【解决方案1】:

您可以这样做,使用对象创建的简写形式:

class Test {
  constructor({a=1, b=2, c=3}={}) {
    Object.assign(this, {a, b, c});
  }
}

例子:

class Test {
  constructor({a=1, b=2, c=3}={}) {
    Object.assign(this, {a, b, c});
  }
}
const t1 = new Test();
console.log("t1:", t1.a, t1.b, t1.c);
const t2 = new Test({b: 42});
console.log("t2:", t2.a, t2.b, t2.c);

或者,不要使用解构,而是对Object.assign使用多个参数:

class Test {
  constructor(options = {}) {
    Object.assign(this, Test.defaults, options);
  }
}
Test.defaults = {a: 1, b: 2, c: 3};

// Usage:
const t1 = new Test();
console.log("t1:", t1.a, t1.b, t1.c);
const t2 = new Test({b: 42});
console.log("t2:", t2.a, t2.b, t2.c);

...如果您希望将其中任何一个作为可以通过名称引用的离散事物,您可以使用this.a(以及this.bthis.c)来执行此操作,或者您可以执行以下操作:

let {a, b, c} = this;

...之后使用这些。 (请注意分配到生成的abc 不会更新对象。)

【讨论】:

  • 不错!没有办法使用 arguments 的等价物访问对象?
  • @hhh:不处理默认值,不。传入的对象确实以arguments[0] 的形式提供,但以原始形式提供,并且仅在传入时才可用。
  • 好的!谢谢,这就是我提问的目的!
  • @hhh:我刚刚为您更新了一个替代方案,我认为您可能会更喜欢它。但不使用解构。
猜你喜欢
  • 2017-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-18
  • 2020-02-18
相关资源
最近更新 更多