0

I have this code, which is kinda long winded but gets there in the end …

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

I thought I might try using destructuring to speed things along, like this:

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

    this.callback = callback;

  }
}

... except that doesn't work. It doesn't even pass syntax muster.

What is a clean and simple way of writing a class constructor that takes an optional params object with various optional parameters that override some default values?

2
  • do you mean you want to destructure params ? Commented Sep 24, 2018 at 5:28
  • @ShubhamGupta umm ... yes? I think that's what it is called. Commented Sep 24, 2018 at 5:31

2 Answers 2

2

You mean something like this?

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 does exactly what you want.

Sign up to request clarification or add additional context in comments.

2 Comments

ooh, Object.assign looks useful
I like this solution. I just learnt .assign() could save a lot of typing like Object.keys().forEach(...). An approach I was going to post.
1

I think the way you are destructuring is incorrect. Try the below code where we destructure from params and then assign the values to this.

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

2 Comments

OK, that is shorter (coding the defaults into the destructure and then assigning those values)
@Erics yes that way it is cleaner as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.