ES6类构造函数参数 [英] ES6 class constructor arguments

查看:179
本文介绍了ES6类构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看一个ES6类的定义,不明白构造函数的参数。这是类:

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

m被这个 {size = null,} = {} 困惑。这是一个单一的参数吗?这是什么意思?

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

推荐答案

这是一个对象解构具有给定的默认值。

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

如果你传递一个obj,

If you pass an obj like

{ size: true }

您可以像正常变量一样访问构造函数中的size

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.

示例:

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

如果你传递一个没有属性的对象foo,那么它将是未定义的,其余的行为就像我上面提到的。

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

另外值得一提的是你必须添加<$在构造函数声明中解构分配结束时,c $ c> = {} 当你不通过任何东西的时候。否则你必须传递一些对象(可能是空的)。

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

这篇关于ES6类构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆