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

后端 未结 2 1029
遇见更好的自我
遇见更好的自我 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条回答
  • 2020-11-27 03:12

    The second example uses destructuring.

    This will call the specific variable (including functions) that are exported from the required module.

    For example (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.

    0 讨论(0)
  • 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?

    0 讨论(0)
提交回复
热议问题