在构造函数中将Class值设置为参数

时间:2018-09-24 05:26:32

标签: javascript class

我有这段代码,虽然有点麻烦,但最终到达了那里……

class WorksButLongWinded {
  constructor (callback, params = {}) {
    // defaults ...
    this.foo = "string";
    this.bar = 200;

    this.callback = callback;

    // params ...
    if( typeof params.foo != "undefined" ) { this.foo = params.foo }
    if( typeof params.bar != "undefined" ) { this.bar = params.bar }
  }
}

我想我可能会尝试使用解构来加快进度,就像这样:

class DoesNotWork {
  constructor (callback, params = {}) {
    {
      this.foo = "string", 
      this.bar = 200
    } = params;

    this.callback = callback;

  }
}

...否则不起作用。它甚至没有通过语法要求。

一种简单而干净的方法是编写一个类构造函数,该类构造函数接受带有可选可选参数的可选params对象,这些可选可选参数会覆盖某些默认值?

2 个答案:

答案 0 :(得分:2)

您的意思是这样的吗?

class WorksButLongWinded {
  constructor(callback, params) {
    let defaults = {
      foo: "string",
      bar: 200
    };

    this.callback = callback;
    Object.assign(this, defaults, params);
  }
}

let a = new WorksButLongWinded(() => {});
console.log(a.foo);  // "string"
console.log(a.bar);  // "200"

let b = new WorksButLongWinded(() => {}, {foo: "bar"});
console.log(b.foo);  // "bar"
console.log(b.bar);  // "200"

Object.assign正是您想要的。

答案 1 :(得分:1)

我认为您解构的方式不正确。尝试下面的代码,在这些代码中从params进行解构,然后为其分配值。

class WorksButLongWinded {
  constructor (callback, params = {}) {
    const {foo = "string", bar = 200} = params;
    this.foo = foo;
    this.bar = bar;
    this.callback = callback;
  }
}