In 2015, ECMA International finalized the ECMAScript 6 specifications and renamed it to ECMAScript 2015 (ES 2015). This means is that we have a new standard in writing JavaScript code.
2015年,ECMA International最终确定了ECMAScript 6规范 ,并将其重命名为ECMAScript 2015(ES 2015) 。 这意味着我们在编写JavaScript代码方面有了新的标准。
听起来不错,可以使用吗? (Sounds cool, can I use it?)
ES2015 comes with a bunch of cool new features that we will briefly discuss later. Now that these features are basically frozen for this iteration, it’s safe to start working with them in full scale production applications.
ES2015具有许多很酷的新功能,我们将在后面简要讨论。 现在,这些功能基本上已在此迭代中冻结,现在可以在大规模生产应用程序中开始使用它们了。
Even more, I encourage you to migrate your old code as soon as you can to the new standard, because any line of code that you write using the previous ES5 standard is obsolete from day 1.
甚至,我鼓励您尽快将旧代码迁移到新标准,因为从第一天开始,使用以前的ES5标准编写的任何代码行都已过时 。
“The future is already here — it’s just not very evenly distributed.” — William Gibson
“未来已经来临–分布不均。” —威廉·吉布森
As you can see in the compatibility table, ES2015 is being adopted at a fast pace by all browsers, even Safari and Microsoft Edge (the fancy name they came up with for the new version of IE). Not all functionality is implemented yet, but you can already use a good chunk of the new features directly in the browser.
从兼容性表中可以看到,所有浏览器,甚至是Safari和Microsoft Edge (新版本IE都想出了这个名字)都正在Swift采用ES2015。 尚未实现所有功能,但是您已经可以直接在浏览器中使用很多新功能。
However, I don’t advise you to write ES2015 code and then run it in directly in browser. Say hello to babel.
但是,我不建议您编写ES2015代码,然后直接在浏览器中运行它。 向通天塔问好 。
Babel.js is a transpiler that you can very easily integrate into your JavaScript build process.
Babel.js是一个编译器 ,您可以非常轻松地将其集成到JavaScript构建过程中。
If you want to learn more about how to use babel for all your JavaScript applications — or how to implement a build process — I encourage you to read this article. Then get yourself familiar with task runners like grunt and gulp, and with module bundlers like webpack and Browserify, because they are slowly but surely becoming industry standards.
如果您想了解更多有关如何在所有JavaScript应用程序中使用babel的信息,或者如何实现构建过程的信息,建议您阅读本文 。 然后让自己熟悉任务跑者像咕噜和一饮而尽 ,并与像模块捆扎机的WebPack和Browserify ,因为他们是缓慢而稳步地成为行业标准。
So we write ES2015 code today, the code gets transpiled into ES5, which is almost 100% supported in most modern browsers. Once most of the major functionalities offered by ES2015 are implemented in the modern browsers, we just get rid of the babel transpiler from our build process. So with a single step we bring our live code to the ES2015 standard.
因此,我们今天编写ES2015代码,该代码被转换为ES5,在大多数现代浏览器中几乎100%支持该代码。 一旦在现代浏览器中实现了ES2015提供的大多数主要功能,我们就从构建过程中摆脱了babel编译器。 因此,只需一步,即可将实时代码带入ES2015标准。
什么是新的? (What’s new?)
I remember being fascinated by the amount of new stuff that ES6 promised to bring, so if you want a complete guide for the new features I can advise you to follow these “tutorials”:
我记得ES6承诺会带来很多新内容,所以如果您想要有关这些新功能的完整指南,我可以建议您遵循以下“教程”:
Now let’s discuss some of my favorite new features.
现在,让我们讨论一些我最喜欢的新功能。
箭头功能 (Arrow Functions)
Arrow functions allow you to write anonymous functions in a much more compact way, dropping a lot of boilerplate code. This paves the way for functional style programming, and allows programmers to keep their sanity while reading functional code written by others.
箭头函数使您可以以更紧凑的方式编写匿名函数,从而删除大量样板代码。 这为功能样式编程铺平了道路,并允许程序员在阅读他人编写的功能代码时保持理智。
The cool part with arrow functions is that you never have the write the word function — except in the cases in which you actually need a named function. Then you read about the new enhanced object literal notation and you realize that the word function is probably going to be forgotten soon.
带有箭头功能的最酷的部分是,您永远不会编写单词函数 - 除非您实际上需要一个命名函数。 然后,您了解了新的增强对象文字表示法,并且意识到单词function可能很快就会被遗忘。
块范围变量 (Block-scoped variables)
Function-scoped variable behavior has long been the climax of any JavaScript interview. ES2015 makes life easier for those who come from C-based programming languages in which a variable is scoped to the block of code in which it is declared. With “let” and “const”, your code is much more expressive. Let’s look at a few examples:
长期以来,函数范围的变量行为一直是所有JavaScript采访的高潮。 ES2015使来自基于C的编程语言的人的工作变得更轻松,在这种语言中,变量的作用域仅限于声明该变量的代码块。 使用“ let ”和“ const ”,您的代码更具表现力。 让我们看几个例子:
As you probably figured it out by now, “let” is equivalent with “var”, but it is block-scoped., This means that it does not exist outside the block in which it is defined.
正如您现在可能已经知道的那样,“ let”等同于“ var” ,但是它是块作用域的。这意味着它在定义它的块之外不存在。
On the other hand, “const” allows you to define a variable with a fixed value. It can only get a value when it is created, and any subsequent assignment to a “const” has no effect. This is very important in terms of expressiveness because you can declare all variables that you do not modify in your code with “const” and all the others with “let.” This way, any value that has the potential to mutate in your code is easily trackable from the beginning. If all your variables are constants (no pun intended) you don’t need to worry about side effects or unwanted state mutations.
另一方面,“ const”允许您定义具有固定值的变量。 它只能在创建时获取值,并且随后对“ const”的任何赋值均无效。 就表达能力而言,这非常重要,因为您可以使用“ const”声明未在代码中修改的所有变量,并使用“ let声明所有其他变量。 ”这样一来,任何有可能在您的代码中发生变异的值都可以从一开始就很容易被跟踪。 如果所有变量都是常量(不需要双关语),则无需担心副作用或不必要的状态突变。
解构 (Destructuring)
Talking about expressiveness, destructuring offers tons of ways of saying more with fewer lines of code. This feature basically does pattern matching on objects and arrays, allowing you to quickly access parts of them.
谈到表达性,销毁提供了无数种方式,用更少的代码行就能表达更多。 此功能基本上对对象和数组进行模式匹配 ,从而使您可以快速访问它们的一部分。
With destructuring, you no longer need to create variables which point to certain properties or to sub-objects of the function parameter, like in the fullName() example above. Also it is easier to return multiple values from one function without writing too many lines of code. Destructuring is fun when it is combined with the new ways of handling function parameters: default parameters and the rest and spread operators.
通过解构,您不再需要创建指向某些属性或函数参数的子对象的变量,就像上面的fullName()示例一样。 同样,从一个函数返回多个值也很容易,而无需编写过多的代码行。 将解构与处理函数参数的新方法(默认参数以及其余运算符和散布运算符)结合使用会很有趣。
函数参数-默认,休息,传播 (Function Parameters — Default, Rest, Spread)
Default parameters are pretty straight-forward, and are already present in many programming languages, so nothing extraordinary here. However the rest and the spread operators allow you to handle function parameters in any way you want.
默认参数非常简单明了,并且已经在许多编程语言中提供了,所以这里没有什么特别的。 但是, 其余和散布运算符允许您以所需的任何方式处理函数参数。
发电机 (Generators)
Ok, we’ve been playing around with the syntax, we’ve made some cool functional style programming snippets, let’s dig deep into one of the most interesting features offered by ES2015, namely generators. Very briefly explained, generators are factory functions for iterators. Still confused? I was too, but let’s look at an example
好的,我们一直在研究语法,我们编写了一些很酷的函数式编程片段,让我们深入研究ES2015提供的最有趣的功能之一,即generators 。 简要解释一下,生成器是迭代器的工厂功能。 还是很困惑? 我也是,但让我们看一个例子
So what is happening here? A generator is basically a function which can be stopped at any time and resumed afterwards. The generator is stopped when the yield statement is executed and it returns whatever value we place next to the yield statement. We use the next() function call to go one step at a time, collecting the value yielded by the generator.
那么这里发生了什么? 生成器基本上是一种功能,可以随时停止然后再恢复。 执行yield语句时,生成器将停止,并返回我们在yield语句旁边放置的任何值。 我们使用next()函数调用一次走一步,收集生成器产生的值。
As an additional feature, you can pass a parameter to the next() function and that parameter is considered the return of the yield statement in the generator. So we basically have a two-way communication between the generator function and the outside world.
作为附加功能,您可以将参数传递给next()函数,并且该参数被视为生成器中yield语句的返回。 因此,我们基本上在生成器功能和外界之间进行了双向通信。
The big deal with generators is their potential to be used in the parts of the code that handle asynchronous calls. Imagine the situation in which you need to perform 3 distinct api calls in a particular order, always using the result of one call as parameter to the next call. Imagine how that code would look like with callbacks or even with promises.
与生成器最重要的是,它们有潜力在处理异步调用的代码部分中使用。 想象一下您需要以特定顺序执行3个不同的api调用的情况,始终将一个调用的结果用作下一个调用的参数。 想象一下,代码在回调甚至承诺中的样子。
What if we can do something like this instead?
如果我们可以做这样的事情怎么办?
There are already working solutions with allow you to write sequential async calls with generators and promises. As an example, you can checkout this article which shows a similar solution.
已经有可行的解决方案,可让您使用生成器和Promise编写顺序的异步调用。 例如,您可以查看本文,该文章显示了类似的解决方案 。
Of course there are many other cool features like string templates, native promises, AMD-style modules, new functions added on the prototypes of Number, String, Array and Object and many more. But I presented here the ones which I consider the most useful in regular coding tasks. However, there’s a dark twist with one of the new features that I want to discuss.
当然,还有许多其他很酷的功能,例如字符串模板,本机promise,AMD样式的模块,在Number,String,Array和Object原型上添加的新功能等等。 但是我在这里介绍了我认为在常规编码任务中最有用的代码。 但是,我要讨论的新功能之一有一个黑暗的转折。
班级 (Classes)
I bet 50% of the people that read the specs were looking forward to this, while the other 50% were saying: “But … why???” I fall into the second category here.
我敢打赌,阅读规格的人中有50%对此表示期待,而其他50%的人则说:“但是……为什么?” 我在这里属于第二类。
ES2015 brings a sugaring syntax which uses prototypal object creation in the back. Here’s an example:
ES2015引入了加糖语法,该语法在后面使用原型对象创建。 这是一个例子:
Get this out of your head, JavaScript does NOT have classes. JavaScript does not implement object oriented programming based on classes nor will it ever do that. The inheritance model in JavaScript is prototypal, objects are created based on the prototypes of other objects. All these syntax elements you see in the class snippet like: constructor, get, set, static are just implemented in the back as regular functions or simple values added on prototypes.
不用担心 ,JavaScript没有类。 JavaScript不会基于类实现面向对象的编程,也不会这样做。 JavaScript中的继承模型是原型,对象是根据其他对象的原型创建的。 您在类片段中看到的所有这些语法元素,例如:构造函数,获取,设置,静态,都只是在后面实现为常规函数或在原型上添加的简单值。
Adding class in JavaScript is probably the worst mistake moving forward. Think how many people misinterpret the meaning of “this”. Multiply that by 10 and you get the number of people that will misinterpret the meaning of “class”.
在JavaScript中添加类可能是前进中最严重的错误。 想想有多少人误解了“ this ”的含义。 将其乘以10,就会得到会误解“ 阶级 ”的含义的人数。
All these constructs are coming from the world of class-based object orientation. People just need to drop these practices, because they do not fit with the paradigms implemented in JavaScript. Further more, they confuse the newcomers more than ever.
所有这些构造都来自基于类的面向对象的世界。 人们只需要放弃这些实践,因为它们不符合JavaScript中实现的范式。 此外,他们比以往任何时候都更使新来者感到困惑。
coming to JavaScript and asking how to do classical inheritance is like picking up a touch-screen mobile phone and asking where the rotary dial is. Of course, people will be amused when the next thing out of your mouth is, “If it doesn’t have a rotary dial, it’s not a telephone!” — Eric Elliott, Programming JavaScript Applications
接触JavaScript并询问如何进行经典继承就像拿起触摸屏手机并询问旋转拨盘在哪里一样。 当然,当您的下口想出的一句话是:“如果没有转盘,那就不是电话!” — Eric Elliott,JavaScript应用程序编程
My standard interview contains the following set of questions I ask in succession:
我的标准面试包含以下我连续提出的问题:
- “Are classes mandatory in OOP?” “在OOP中必须上课吗?”
- “Is JavaScript an OOP language?” “ JavaScript是一种OOP语言吗?”
- “Does it have classes?” “有课吗?”
Imagine how much time I will potentially waste trying to explain to people that the “classes” that they see in JavaScript are actually NOT classes.
想象一下,我可能在浪费时间去向人们解释他们在JavaScript中看到的“类”实际上不是类。
拥抱功能编程 (Embrace Functional Programming)
On the bright side, with ES2015 we have all these new features that allow us to write better, cleaner and at a certain extent faster code. I think that now is the time to embrace functional programming as the fundamental paradigm in JavaScript. Preferably, you won’t have to write a single loop statement ever again, except in some rare situations.
从好的方面来说,ES2015拥有所有这些新功能,使我们能够编写更好,更简洁且在某种程度上更快的代码。 我认为现在是时候将函数式编程作为JavaScript的基本范例了。 最好,除了在极少数情况下,您不必再写一个循环语句。
With const and let you are able to add another level of expressiveness to all your variables. You will probably avoid using var from this point on. Arrow functions combined with classic iterator functions are letting you write functional reactive programming, basically creating streams of functionality.
随着常量 , 让你能够表现的另一个级别添加到您的所有变量。 从那时起,您可能会避免使用var 。 箭头函数与经典的迭代器函数结合在一起,使您可以编写函数式React式编程,基本上可以创建功能流。
Your code becomes more succinct, more functional and less stateful. This also means that your code is easier to test and to maintain, and also far less prone to bugs, and feature pure functions, immutable data. There’s a lot of content out there on the benefits of functional programming, and I think that iterating over those points again doesn’t make sense in the scope of this article.
您的代码变得更加简洁,功能更多,状态更少。 这也意味着您的代码更易于测试和维护,并且更不容易出现错误,并且具有纯函数,不可变数据。 关于函数式编程的好处有很多内容,我认为再次迭代这些要点在本文的范围内没有意义。
Working with Babel isn’t that hard, and I encourage you to start doing it today. Remember, code that you write today using ES5 syntax is obsolete. Fair and simple.
与Babel合作并不难,我鼓励您立即开始工作。 请记住,您今天使用ES5语法编写的代码已过时。 公平而简单。
下一步是什么? (What’s next?)
ES2015 was a huge release with a lot of changes. The TC39 committee started with a different approach and they will standardize new features each year, basically splitting what was originally intended to be implemented as ES7 into smaller chunks.
ES2015是一个巨大的版本,具有很多更改。 TC39委员会以不同的方式开始,他们将每年标准化新功能,基本上将最初打算作为ES7实现的功能分成较小的部分。
Some of the future features of JavaScript will include: async functions, object/function decorators and things like SIMD (single instruction, multiple data) operations.
JavaScript的一些将来的功能将包括:异步函数,对象/函数装饰器以及SIMD(单指令,多数据)操作之类的东西。
Usually all future features are called generically ESnext, in case you see this anywhere. With Babel, you can even play with some of these future features today!
通常,将来所有的功能都统称为ESnext,以防万一。 使用Babel,您甚至可以立即使用其中的某些将来功能!
Here are some articles I recommend reading regarding ESnext features:
我建议阅读以下有关ESnext功能的文章:
https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841#.hrg2xk5q1
https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841#.hrg2xk5q1
https://www.twilio.com/blog/2015/10/asyncawait-the-hero-javascript-deserved.html
https://www.twilio.com/blog/2015/10/asyncawait-the-hero-javascript-deserved.html
https://github.com/tc39/ecma262 (official status of features)
https://github.com/tc39/ecma262 (功能的官方状态)
翻译自: https://www.freecodecamp.org/news/start-writing-modern-javascript-code-f98eccb4841/