ES6 class constructor arguments
Asked Answered
N

1

13

I'm looking at an ES6 class definition and don't understand the arguments to the constructor. Here's the class:

export class Modal {
    constructor($modal, {size = null,} = {}) {
        // stuff
    }
}

I'm confused by this {size = null,} = {}. Is that a single argument? What does it mean?

Novikoff answered 5/5, 2016 at 18:54 Comment(1)
C
13

It's an object destructuring with a given default value.

If you pass an obj like

{ size: true }

you can access the "size" inside the constructor like a normal variable

export class Modal {
  constructor($modal, {size = null } = {}) {
    console.log(size); // prints the size value from the given object
  }
}

If you don't pass anything or you pass an object without "size", size will be null. You can make more of such assignments. Just seperate them by commas.

Example:

constructor($modal, { size = null, foo, bar = "test" } = {})

In this case if you pass an object without property "foo" it will be undefined, the rest acts like I mentioned above.

Also it's worth mentioning that you have to add = {} at the end of destructuring assignment in the constructor declaration. It's in case when you don't pass anything. Otherwise you would have to pass some object (may be empty).

Chlorinate answered 5/5, 2016 at 18:57 Comment(2)
Well, it's not really an assignment in this case…Rectilinear
@bergi It should be an object destructuring, right? CorrectedChilpancingo

© 2022 - 2024 — McMap. All rights reserved.