【问题标题】:Curly brackets (braces) in Node.js 'require' statementNode.js 'require' 语句中的大括号(大括号)
【发布时间】:2016-12-04 05:48:40
【问题描述】:

我试图了解下面两个“要求”语句之间的区别。

具体来说,{ }s 包裹 ipcMain 的目的是什么?

const electron = require('electron')

const {ipcMain} = require('electron')

它们似乎都分配了electron 模块的内容,但它们的功能显然不同。

谁能解释一下?

【问题讨论】:

    标签: javascript node.js ecmascript-6 destructuring


    【解决方案1】:

    第二个例子使用解构。

    这将调用从所需模块导出的特定变量(包括函数)。

    例如(functions.js):

    module.exports = {
       func1,
       func2
    }
    

    包含在您的文件中:

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

    现在您可以单独调用它们,

    func1()
    func2()
    

    相对于:

    const Functions = require('./functions')
    

    使用点表示法调用:

    Functions.func1()
    Functions.func2()
    

    希望这会有所帮助。

    你可以阅读解构here,它是 ES6 中非常有用的部分,可以与数组和对象一起使用。

    【讨论】:

    • 当我在节点REPL中输入{1, 2, 3}并得到3时会发生什么样的解构?
    【解决方案2】:

    使用const electron = require('electron')ipcMain 模块将以electron.ipcMain 的形式提供。

    对于const {ipcMain} = require('electron')ipcMain 模块将作为ipcMain 提供。

    此构造称为object destructuring,实现与 Python 构造相同

    from library import ...
    

    在其基本形式中,它允许您直接引用对象的属性:

    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)
    

    检查:

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

    您可以使用解构赋值来导入 JavaScript 对象的多个属性,例如:

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

    如果您使用不存在的属性,则会将其设置为undefined,您不会收到错误消息。

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

    另请参阅:What does curly brackets in the var { … } = … statements do?

    【讨论】:

      猜你喜欢
      • 2019-07-11
      • 2013-08-16
      • 2021-11-28
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      相关资源
      最近更新 更多