带大括号{}的Javascript构造函数

问题描述 投票:0回答:3

我是javascript新手。我正在看预先编写的代码。我不明白大括号中的内容:{constructor({零件,工具,数据库})

class MyMenu {
  constructor({parts, tools, database}) 
 {
     ...
    this.database = database;   
    this.tools = this._myTools(tools);
    this.parts = this._myParts(parts);
    ..
 }

some code here

functions()
...
...
}
javascript constructor
3个回答
1
投票

这称为解构。例如

const obj = { a: 1, b: 2 };

// you can get value of a using destructuring like this

const { a } =  obj;

console.log(a);

// Similarly, this applies to function arguments

//e.g.

const personData = { firstName: 'John', lastName: 'Doe', age: 20 };


class Person {
   constructor ({ firstName, lastName, age }) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
   }
}

const person = new Person(personData);

console.log(person.firstName);


0
投票

这是解构,这是一个了不起的功能!

o = {key1: 'value1', key2: 'value2'}
const {key2} = o
console.log(key2)

从本质上讲,这是一种将元素从对象中拉出而不必遍历整个对象的方法。

© www.soinside.com 2019 - 2024. All rights reserved.