最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ES6 class constructor arguments - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Jul 12, 2024 at 11:16 matronator 5547 silver badges16 bronze badges asked May 5, 2016 at 18:54 flyingL123flyingL123 8,09613 gold badges74 silver badges137 bronze badges 1
  • 2 possible duplicate of Where can I get info on the object parameter syntax for javascript functions? and what does (state = {}) => state means – Bergi Commented May 5, 2016 at 19:11
Add a ment  | 

1 Answer 1

Reset to default 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 mas.

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).

发布评论

评论列表(0)

  1. 暂无评论