简体   繁体   English

Node.js“require”语句中的大括号(大括号)

[英]Curly brackets (braces) in Node.js 'require' statement

I am trying to understand the difference between the two 'require' statements below.我试图理解下面两个“要求”语句之间的区别。

Specifically, what is the purpose of the { } s wrapped around ipcMain ?具体来说,围绕ipcMain{ }的目的是什么?

const electron = require('electron')

const {ipcMain} = require('electron')

They both appear to assign the contents of the electron module, but they obviously function differently.它们似乎都分配了electron模块的内容,但它们的功能显然不同。

Can anyone shed some light?任何人都可以透露一些信息吗?

The second example uses destructuring.第二个例子使用解构。

This will call the specific variable (including functions) that are exported from the required module.这将调用从所需模块导出的特定变量(包括函数)。

For example (functions.js):例如(functions.js):

module.exports = {
   func1,
   func2
}

is included in your file:包含在您的文件中:

const { func1, func2 } = require('./functions')

Now you can call them individually,现在你可以单独调用它们,

func1()
func2()

as opposed to:与:

const Functions = require('./functions')

are called using dot notation:使用点表示法调用:

Functions.func1()
Functions.func2()

Hope this helps.希望这可以帮助。

You can read about destructuring here , it is a very useful part of ES6 and can be used with arrays as well as objects.您可以在此处阅读有关解构的信息,它是 ES6 中非常有用的部分,可以与数组和对象一起使用。

With const electron = require('electron') , the ipcMain module will be available as electron.ipcMain .使用const electron = require('electron')ipcMain模块将作为electron.ipcMain可用。

With const {ipcMain} = require('electron') the ipcMain module will be available as ipcMain .使用const {ipcMain} = require('electron') ipcMain模块将作为ipcMain可用。

This construct is called object destructuring and achieves the same as the Python construct这种构造称为对象解构,其实现与 Python 构造相同

from library import ...

In its basic form it allows you to refer to the properties of an object directly:在其基本形式中,它允许您直接引用对象的属性:

var o = {prop1: '1', prop2: 2}
var {prop1, prop2} = o
console.log(prop1) // '1' (same as o.prop1)
console.log(prop2) // 2 (same as o.prop2)

Check:查看:

const {ipcMain} = require('electron')
const myElectron = require('electron')
const myipcMain = myElectron.ipcMain
console.log(myipcMain===ipcMain) // true

You can use the destructuring assignment to import multiple properties of a JavaScript object, eg:您可以使用解构赋值来导入 JavaScript 对象的多个属性,例如:

const { app, BrowserWindow, ipcMain } = require('electron')

If you use a property that doesn't exist, this will be set to undefined and you won't get an error.如果您使用不存在的属性,这将被设置为undefined并且您不会收到错误消息。

const {app, BrowserWindow, ipcMain, doesntExist} = require('electron')
console.log(doesntExist) // undefined

See also: What does curly brackets in the var { … } = … statements do?另请参阅: var { … } = …语句中的大括号有什么作用?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM