带花括号的 Javascript (ES6) const
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33798717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript (ES6) const with curly braces
提问by tralston
I'm new to ECMAScript 6, and while trying to learn Ember, I've seen the following code style occassionally:
我是 ECMAScript 6 的新手,在尝试学习 Ember 时,我偶尔会看到以下代码样式:
const {
abc,
def
} = Object;
I've searched Google and many sites explaining the new ES6 specifications. I know this is not the current implementation, because my console gives an error when I input that.
我搜索过谷歌和许多解释新 ES6 规范的网站。我知道这不是当前的实现,因为当我输入时我的控制台会出错。
What does this code mean?
这段代码是什么意思?
UPDATE
更新
I pasted this snippet into Babel's transpiler, and this is what it returned:
我将此代码段粘贴到Babel 的 transpiler 中,这是它返回的内容:
"use strict";
var abc = Object.abc;
var def = Object.def;
I'm still confused as to what this is trying to accomplish.
我仍然对这要实现的目标感到困惑。
回答by Dan Prince
It is an ES2015 destructuring assignment. More specifically, it's Object Destructuring
It might help to see it rewritten in a more verbose way.
以更详细的方式重写它可能会有所帮助。
const abc = Object.abc;
const def = Object.def;
It's a syntatically terse way of extracting properties from objects, into variables.
这是从对象中提取属性到变量中的一种语法简洁的方式。
// you can rewrite this
const name = app.name;
const version = app.version;
const type = app.type;
// as this
const { name, version, type } = app;
Browser vendors are still implementingthe ES2015 specification which is probably why it didn't work in your browser.
浏览器供应商仍在实施ES2015 规范,这可能是它在您的浏览器中不起作用的原因。
However, there's a project called Babelwhich allows you to convert future specifications of Javascript back into ES5. You can try out ES2015 code in their REPL.
但是,有一个名为Babel的项目,它允许您将未来的 Javascript 规范转换回 ES5。您可以在他们的 REPL 中试用 ES2015 代码。