[英]What does {app, BrowserWindow} means in JavaScript (node.js)?
While reading docs of making softwares with electron , I came across this type of code in the beginning of index.js
file (the file where generally execution starts) 在阅读使用电子制作软件的文档时,我在
index.js
文件的开头遇到了这种类型的代码(通常执行开始的文件)
const {app, BrowserWindow} = require('electron')
What does {app, BrowserWindow}
(the syntax, not the keywords) really means? 什么
{app, BrowserWindow}
(语法,而不是关键字)真正意味着什么? Is it a JavaScript syntax, or a node.js thing or something exclusively related to electron? 它是一种JavaScript语法,还是一个与电子完全相关的node.js之物?
This syntax is called 'object destructuring', and it is a feature of the latest version of JavaScript (JavaScript2015 aka ECMAScript 6/ES6) - app
and BrowserWindow
are just particular parts of electron
that you want to use in this portion of your application. 这种语法称为“对象解构”,它是最新版JavaScript(JavaScript2015又名ECMAScript 6 / ES6)的一个特性 -
app
和BrowserWindow
只是您希望在应用程序的这一部分中使用的electron
特定部分。
It's a way to simplify your code and to easily reference critical parts of a dependency. 这是一种简化代码并轻松引用依赖关键部分的方法。
Here's a very basic example from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment 以下是https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment中的一个非常基本的示例
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
So in your case, electron
is an imported module that would look something like (again, a gross oversimplification here): 所以在你的情况下,
electron
是一个看起来像的导入模块(再次,这里是一个粗略的过度简化):
var electron = {
app: {
greet: () => {
console.log("Hello, world!")
}
},
BrowserWindow: {/* some other stuff */},
anotherMethod: {/* other stuff, which we will ignore in your app */}
}
module.exports electron
Then in your app, you import this module and you can reference the imported attributes directly: 然后在您的应用程序中导入此模块,您可以直接引用导入的属性:
const {app, BrowserWindow} = require('electron')
app.greet()
// "Hello, world!"
And similarly, you can reference BrowserWindow
... however, you couldn't reference anotherMethod
without including it in the destructuring assignment. 同样,你可以参考
BrowserWindow
......但是,你不能引用anotherMethod
而不包括它在解构赋值。
Hope that's helpful. 希望这很有帮助。
I just want to point out (because the OP wonders what destructuring is useful for), that the statement in your question is equivalent to: 我只是想指出(因为OP想知道什么是解构是有用的),你问题中的陈述相当于:
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
However, using object destructuring, it becomes more succinct and leaves out the unnecessary declaration of the const electron
: 但是,使用对象解构,它变得更简洁,并且省略了不需要的
const electron
声明:
const {app, BrowserWindow} = require('electron')
This is why I use it very often. 这就是我经常使用它的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.