Javascript (ES6) const with curly braces [duplicate]

夙愿已清 提交于 2019-12-17 21:41:46

问题


I'm new to ECMAScript 6, and while trying to learn Ember, I've seen the following code style occassionally:

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.

What does this code mean?

UPDATE

I pasted this snippet into Babel's transpiler, and this is what it returned:

"use strict";

var abc = Object.abc;
var def = Object.def;

I'm still confused as to what this is trying to accomplish.


回答1:


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 implementing the ES2015 specification which is probably why it didn't work in your browser.

However, there's a project called Babel which allows you to convert future specifications of Javascript back into ES5. You can try out ES2015 code in their REPL.



来源:https://stackoverflow.com/questions/33798717/javascript-es6-const-with-curly-braces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!