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

后端 未结 2 1048
遇见更好的自我
遇见更好的自我 2020-11-27 03:11

I am trying to understand the difference between the two \'require\' statements below.

Specifically, what is the purpose of the { }s wrapped around

2条回答
  •  猫巷女王i
    2020-11-27 03:28

    With const electron = require('electron'), the ipcMain module will be available as electron.ipcMain.

    With const {ipcMain} = require('electron') the ipcMain module will be available as ipcMain.

    This construct is called object destructuring and achieves the same as the Python construct

    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, e.g.:

    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.

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

    See also: What does curly brackets in the var { … } = … statements do?

提交回复
热议问题