问题
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)
const {app, BrowserWindow} = require('electron')
What does {app, BrowserWindow}
(the syntax, not the keywords) really means? Is it a JavaScript syntax, or a node.js thing or something exclusively related to electron?
回答1:
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.
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
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):
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.
Hope that's helpful.
回答2:
I just want to point out (because the OP wonders what destructuring is useful for), that the statement in your question is equivalent to:
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 {app, BrowserWindow} = require('electron')
This is why I use it very often.
来源:https://stackoverflow.com/questions/44732946/what-does-app-browserwindow-means-in-javascript-node-js