by Todd Palmer
托德·帕爾默(Todd Palmer)
使用一些我喜歡的東西開始使用ES6 (Getting started with ES6 using a few of my favorite things)
This tutorial walks you through some easy steps to get started learning the newest version of JavaScript: ES6.
本教程將引導您完成一些簡單的步驟,以開始學習最新版本JavaScript: ES6。
To get a feel for the language, we will delve into a few of my favorite features. Then I will provide a short list of some great resources for learning ES6.
為了體會這種語言,我們將深入研究我最喜歡的一些功能。 然后,我將提供一些簡短的清單,其中包含一些學習ES6的重要資源。
ES6或ECMAScript 2015? (ES6 or ECMAScript 2015?)
“What’s in a name?”
“名字叫什么?”
“What’s in a name?” ― Juliet from Shakespeare’s “Romeo and Juliet”
“名字叫什么?” ―莎士比亞的《羅密歐與朱麗葉》中的朱麗葉
The official name of the 6th Edition of ECMAScript is ECMAScript 2015, as it was finalized in June, 2015. However, in general, people seem to refer to it simply as ES6.
第六版ECMAScript的正式名稱為ECMAScript 2015,該版本于2015年6月完成。但是,總的來說,人們似乎將其簡稱為ES6 。
Previously, you had to use a transpiler like Babel to even get started with ES6. Now, it seems that just about everybody except Microsoft Internet Explorer supports most of the features in ES6. To be fair, Microsoft does support ES6 in Edge. If you want more details, take a look at kangax’s compatibility table.
以前,您必須使用transpiler像巴貝爾連得與ES6開始。 現在,似乎除了Microsoft Internet Explorer之外,幾乎所有人都支持ES6中的大多數功能。 公平地說,Microsoft確實在Edge中支持ES6。 如果您需要更多詳細信息,請查看kangax的 兼容性表 。
ES6學習環境 (ES6 Learning Environment)
The best way to learn ES6 is to write and run ES6. There are may ways to do that. But the two that I use when I am experimenting are:
學習ES6的最好方法是編寫和運行ES6。 有很多方法可以做到這一點。 但是我在實驗中使用的兩個是:
Node.js
Node.js
Babel.io’s Try it out page
Babel.io的“ 試用”頁面
Node.js和Visual Studio代碼 (Node.js and Visual Studio Code)
One of the best ways to explore the pleasantries of ES6 is to write your code in an editor like Visual Studio Code and then run it in Node.js
探索ES6樂趣的最佳方法之一是在諸如Visual Studio Code之類的編輯器中編寫代碼 ,然后在Node.js中運行它
Install Visual Studio Code and create a file called helloworld.js
. Paste the following code in:
安裝Visual Studio Code并創建一個名為helloworld.js
的文件。 將以下代碼粘貼到:
console.log('Hello world');
Save it. It should look something like this:
保存。 它看起來應該像這樣:
Since version 6.5, Node.js has supported most of the ES6 standard. To run our example, open the Node.js Command Prompt to your folder where you created the helloworld.js
file. And, just type:
從6.5版開始,Node.js支持大多數ES6標準。 要運行我們的示例,請在創建helloworld.js
文件的文件夾中打開Node.js命令提示符。 并且,只需鍵入:
node helloworld.js
Our console.log
statement prints as output:
我們的console.log
語句輸出為輸出:
Babel.io (Babel.io)
It isn’t as much fun as Node.js, but a convenient way to run ES6 code is the Try it out page on Babel.io. Expand the Settings and make sure Evaluate is checked. Then open your browser Console.
它不如Node.js有趣,但是運行ES6代碼的便捷方法是Babel.io上的“ 試用”頁面。 展開設置 ,并確保選中評估 。 然后打開瀏覽器控制臺 。
Type the ES6 into the column on the left. Babel compiles it to plain old JavaScript. You can use console.log
and see the output in the Web Console on the right.
在左側欄中輸入ES6。 Babel將其編譯為普通的舊JavaScript。 您可以使用console.log
并在右側的Web控制臺中查看輸出。
我最喜歡的一些功能 (Some of My Favorite Features)
“These are a few of my favorite things.”
“這些是我最喜歡的一些東西。”
In this section, we will take a quick look at just a few of the new features of ES6 including:
在本節中,我們將快速瀏覽一下ES6的一些新功能,包括:
Using
let
andconst
instead ofvar
使用
let
和const
代替var
- Arrow functions 箭頭功能
- Template Strings 模板字符串
- Destructuring 解構
const并讓Versus var (const and let Versus var)
Now that you are coding in ES6: Stop using var
! Seriously, never use var
again.
現在您正在ES6中進行編碼:停止使用var
! 認真地說,永遠不要再使用var
。
From now on, use either const
or let
. Use const
when you will set the value once. Use let
when you intend to change the value.
從現在開始,使用const
或let
。 一次設置值時,請使用const
。 當您打算更改值時,請使用let
。
let bar = { x: 'x'};const foo = { x: 'x'};
bar.x = 'other'; // This is finefoo.x = 'other'; // This is fine
bar = {}; // This is also finefoo = {}; // This will throw an error
Typically, I like to use const
first. Then if it complains, I look at my code and make sure I really need to be able to modify the variable. If so, I change it to let
.
通常,我喜歡先使用const
。 然后,如果出現問題,請查看我的代碼,并確保確實需要修改該變量。 如果是這樣,我將其更改為let
。
Make sure you check out the resources later in this article for more information on let
and const
. You will see that they work much more intuitively than var
.
確保您在本文后面查看資源,以獲取有關let
和const
更多信息。 您會發現它們比var
更直觀地工作。
箭頭功能 (Arrow Functions)
Arrow functions are one of the defining features of ES6. Arrow functions are a new way to write functions. For example, the following functions work identically:
箭頭功能是ES6的定義功能之一。 箭頭函數是編寫函數的新方法。 例如,以下功能完全相同:
function oneMore(val){ return val+1;}console.log('3 and one more is:', oneMore(3));
const oneMore = (val) => val+1;console.log('3 and one more is:', oneMore(3));
There are a few things to remember about arrow functions:
關于箭頭功能,需要記住以下幾點:
- They automatically return the computed value. 它們自動返回計算值。
They have lexical
this
.他們有
this
詞匯。
This first time I saw this I wondered, “What in the wide world is a lexical this? And, do I really care?” Let’s look at an example of why the lexical this is so useful and how it makes our code so much more intuitive:
這是我第一次看到這個問題,我想知道:“在世界范圍內,這是什么詞匯 ? 而且,我真的在乎嗎?” 讓我們看一個為什么詞法如此有用以及如何使我們的代碼更加直觀的示例:
In lines 1–31, we define a Class called ThisTester
. It has two functions thisArrowTest()
and thisTest()
that basically do the same thing. But, one uses an arrow function and the other uses the classic function notation.
在第1至31行中,我們定義了一個名為ThisTester
的類。 它有兩個函數thisArrowTest()
和thisTest()
基本上可以完成相同的操作。 但是,一個使用箭頭功能,另一個使用經典功能符號。
On line 33, we create an new object myTester
based on our ThisTester
class and call the two functions in our class.
在第33行,我們基于ThisTester
類創建一個新對象myTester
,并在類中調用這兩個函數。
const myTester = new ThisTester();console.log('TESTING: thisArrowTest');myTester.thisArrowTest();console.log('');console.log('TESTING: thisTest');myTester.thisTest();
In the thisTest()
function, we see that it tries to use this
in line 26.
在thisTest()
函數中,我們看到它嘗試在第26行中使用this
。
console.log('function this fails', this.testValue);
But, it fails because that function gets its own this
and it isn’t the same this
as the class. If you think this is confusing, that’s because it is. It isn’t intuitive at all. And, new developers sometimes spend their first week fighting with this
in callback functions and promises like I did.
但是,它失敗,因為該函數都有自己的this
,這是不一樣的this
作為類。 如果您認為這令人困惑,那是因為。 這根本不是直觀的。 而且,新的開發者有時花自己的第一個星期的戰斗與this
回調函數和承諾,像我一樣。
Eventually, after reviewing a bunch of examples, I figured out the standard “trick” of using a variable called self
to hold onto the this
that we want to use. For example, in line 17:
最終,在回顧了許多示例之后,我得出了使用名為self
的變量來保留我們要使用的this
的標準“技巧”。 例如,在第17行中:
let self = this;
However, notice how in the arrow function in line 10, we can directly access this.testValue
and magically it works:
但是,請注意在第10行的箭頭函數中,我們如何直接訪問this.testValue
并神奇地工作:
let myFunction = (x) =>console.log('arrow "this" works:', this.testValue)
That is lexical this in action. The this
in the arrow function is the same as the this
in the surrounding function that calls it. And hence we can intuitively use this
to access the properties in our object like this.testValue
.
這實際上是詞匯上的 。 在this
箭頭的功能是一樣的this
周圍函數調用它。 因此,我們可以直觀地使用this
來訪問對象中的屬性,例如this.testValue
。
模板字符串 (Template Strings)
Template Strings (sometimes called Template Literals) are an easy way to construct strings. They are great for multi line strings such as those used in Angular templates. Template Strings use the back tick ` instead of quote or apostrophe.
模板字符串(有時稱為模板文字)是一種構造字符串的簡便方法。 它們非常適合多行字符串,例如Angular模板中使用的字符串。 模板字符串使用反引號`代替引號或撇號。
Here is an example of creating a long, multi-line string:
這是創建長的多行字符串的示例:
const myLongString = `This stringactually spans many lines.And, I don't even need to use any "strange"notation.`;console.log (myLongString);
You can easily bind variables to your string, for example:
您可以輕松地將變量綁定到字符串,例如:
const first = 'Todd', last = 'Palmer';console.log(`Hello, my name is ${first} ${last}.`)
Looking at that variable assignment begs the question:“What if I need to use the $
, {
, or }
characters in my string?”
查看該變量賦值為一個問題:“如果我需要在字符串中使用$
, {
或}
字符怎么辦?”
Well, the only one that needs special treatment is the sequence ${
.
好吧,唯一需要特殊處理的是序列${
。
console.log(`I can use them all separately $ { }`);console.log(`$\{ needs a backslash.`);
Template Strings are especially useful in Angular and AngularJS where you create HTML templates, because they tend to be multi-line and have a lot of quotes and apostrophes. Here is what a small example of an Angular Template leveraging the back tick looks like:
模板字符串在創建HTML模板的Angular和AngularJS中特別有用,因為它們往往是多行的,并且帶有很多引號和撇號。 這是一個利用反向刻度的Angular模板的小例子:
import { Component } from '@angular/core';
@Component({ selector: 'app-root', template: ` <h1>{{title}}</h1> <h2>My favorite hero is: {{myHero}}</h2> `})export class AppComponent { title = 'Tour of Heroes'; myHero = 'Windstorm';}
解構 (Destructuring)
Destructuring lets you take parts of an object or array and assign them to your own named variables. For more information on Destructuring, check out my article on ITNEXT.
通過解構,您可以將對象或數組的一部分分配給自己的命名變量。 有關解構的更多信息,請查看我在ITNEXT上的文章 。
ES6資源 (ES6 Resources)
That was just a quick overview of a few of the new features in ES6. Here are some great resources for continuing your journey down the path of learning ES6:
這只是ES6中一些新功能的快速概述。 這里有一些很棒的資源,可以幫助您繼續學習ES6:
Learn ES2015 on Babel
在Babel上學習ES2015
This is an overview of all the new features. Although it doesn’t go into much depth, this is a great page to keep as a quick reference with examples.
這是所有新功能的概述。 盡管沒有深入探討,但這是一個很好的頁面,可以作為示例快速參考。
ES6 tips and tricks to make your code cleaner, shorter, and easier to read! by Sam Williams
ES6技巧和竅門,使您的代碼更簡潔,更短且更易于閱讀! 通過山姆·威廉姆斯
This is a great article in
這是一篇很棒的文章
Free Code Camp’s Medium publication.
免費Code Camp的中刊。
MPJ’s video series: ES6 JavaScript Features
MPJ的視頻系列: ES6 JavaScript功能
If you prefer videos, MPJ is your guy. Not only is he good technically, his stuff is really entertaining.
如果您喜歡視頻,MPJ是您的理想選擇。 他不僅在技術上出色,而且他的東西確實很有趣。
ES6 in Depth series on Mozilla Hacks
深入探討Mozilla Hacks的 ES6系列
This is an excellent in depth series.
這是深度系列中的一個極好的選擇。
Eric Elliott’s series Composing Software
Eric Elliott的系列作曲軟件
Read through this one for a real challenge. Be forewarned though, some of Eric’s stuff is college level Computer Science.
通讀此書,這是一個真正的挑戰。 但是請注意,Eric的一些東西是大學水平的計算機科學。
This article is based on a lecture I gave in March 2018.
本文基于我在2018年3月進行的一次演講。
翻譯自: https://www.freecodecamp.org/news/getting-started-with-es6-using-a-few-of-my-favorite-things-ac89c27812e0/