0

I'm trying to define a constructor with the following behavior for an options argument:

class Test {
  constructor({
    someOption = 'foo',
    otherOption = 'bar',
    aSeedOfSomeSort = Math.random(),
    // ...
  }) {
    console.log(
      someOption, otherOption, aSeedOfSomeSort
    );
  }
}

new Test({someOption: 'lol'});
new Test({otherOption: 'derp'});
new Test({aSeedOfSomeSort: 0.5});
new Test({});
new Test(); // here's the problem

This works great, however, I want the constructor to work so that to use all default parameters, I don't have to pass an empty object. I don't care if the object itself is named or not in the arguments, but in the context of the constructor, I want a clean way to directly access all the options without a namespace or using with.

Is this possible?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153

1 Answers1

5

In the constructor, use this:

constructor({
  someOption = 'foo',
  otherOption = 'bar',
  aSeedOfSomeSort = Math.random(),
  // ...
} = {})

By adding = {} at the end, it becomes the default value of the input parameter if not defined.

Example

Yan Foto
  • 10,850
  • 6
  • 57
  • 88
Sunny Pun
  • 726
  • 5
  • 14
  • Is there a case where this can cause problems due to objects being passed as references - or am I just too paranoid? – jave.web Mar 13 '22 at 13:26
  • 1
    afaik, there is no way to mutate the values inside the object reference in JavaScript (except inside this closure) -- on the client side, even with Web Worker, they should be acting on copies of JS Objects. On the server side (NodeJS), it is concurrent but not parallel. See if this link answers your doubt: https://bytearcher.com/articles/parallel-vs-concurrent/ – Sunny Pun Mar 26 '22 at 18:16