在javascript中const和const {}有什么区别

当我学习电子时,我find了两种获取BrowserWindow对象的方法。

const {BrowserWindow} = require('electron') 

 const electron = require('electron') const BrowserWindow = electron.BrowserWindow 

在javascript中const和const {}有什么区别,我不明白为什么'const {}'可以工作。我错过了什么重要的JS?

这两段代码是等价的,但第一个是使用ES6解构赋值更短。

这是一个如何工作的简单例子:

 const obj = { name: "Fred", age: 42, id: 1 } //simple destructuring const { name } = obj; console.log("name", name); //assigning multiple variables at one time const { age, id } = obj; console.log("age", age); console.log("id", id); //using different names for the properties const { name: personName } = obj; console.log("personName", personName); 

这是ES6的新function之一。 大括号符号是所谓的destructing assignment 。 这意味着你不再需要获取对象本身,并为每个属性分配你想要在不同的行上的variables,你可以这样做:

 const obj = { prop1: 1, prop2: 2 } // previously you would need to do something like this: const firstProp = obj.prop1; const secondProp = obj.prop2; console.log(firstProp, secondProp); // etc. // however now you can do this on the same line: const {prop1, prop2} = obj; console.log(prop1, prop2);