博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用一些我喜欢的东西开始使用ES6
阅读量:2520 次
发布时间:2019-05-11

本文共 9958 字,大约阅读时间需要 33 分钟。

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 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 .

以前,您必须使用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。 有很多方法可以做到这一点。 但是我在实验中使用的两个是:

  • Babel.io’s 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 and then run it in

探索ES6乐趣的最佳方法之一是在诸如类的编辑器中编写 ,然后在运行它

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 page on . Expand the Settings and make sure Evaluate is checked. Then open your browser Console.

它不如Node.js有趣,但是运行ES6代码的便捷方法是上的“ 页面。 展开设置 ,并确保选中评估 。 然后打开浏览器控制台

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 and const instead of var

    使用letconst代替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.

从现在开始,使用constlet 。 一次设置值时,请使用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.

确保您在本文后面查看资源,以获取有关letconst更多信息。 您会发现它们比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 and 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模板的小例子:

import { Component } from '@angular/core';
@Component({  selector: 'app-root',  template: `    

{
{title}}

My favorite hero is: {
{myHero}}

`})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 .

通过解构,您可以将对象或数组的一部分分配给自己的命名变量。 有关更多信息,请查看我在上的 。

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:

  • on Babel

    在Babel上

    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.

    这是所有新功能的概述。 尽管没有深入探讨,但这是一个很好的页面,可以作为示例快速参考。

  • by

    通过

    This is a great article in

    这是一篇很棒的文章

    Medium publication.

    中刊。

  • ’s video series:

    的视频系列:

    If you prefer videos, MPJ is your guy. Not only is he good technically, his stuff is really entertaining.

    如果您喜欢视频,MPJ是您的理想选择。 他不仅在技术上出色,而且他的东西确实很有趣。

  • series on

    探讨 系列

    This is an excellent in depth series.

    这是深度系列中的一个极好的选择。

  • Eric Elliott’s series

    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月进行的一次演讲。

翻译自:

转载地址:http://bcgwd.baihongyu.com/

你可能感兴趣的文章
C语言实现UrlEncode编码/UrlDecode解码
查看>>
返回用户提交的图像工具类
查看>>
树链剖分 BZOJ3589 动态树
查看>>
挑战程序设计竞赛 P131 区间DP
查看>>
【例9.9】最长公共子序列
查看>>
NSFileManager打印目录下的文件的函数
查看>>
Selenium自动化-调用Mysql数据库
查看>>
项目一
查看>>
[转载]AAF灵便应用框架简介系列(6):休息一下,泛谈面向对象 Why OO+多层结构?...
查看>>
android EditView ime
查看>>
javascript 学习随笔7
查看>>
<P>标签小细节
查看>>
Linux 命令 - netstat
查看>>
mac 关闭&&显示隐藏文件命令
查看>>
JavaScript 循环绑定之变量污染
查看>>
poj 1038 Bugs Integrated, Inc. 三进制状态压缩 DFS 滚动数组
查看>>
zoj 1654 Place the Rebots 最大独立集转换成二分图最大独立边(最大匹配)
查看>>
Wordpress解析系列之PHP编写hook钩子原理简单实例
查看>>
怎样看待个体经济
查看>>
不明觉厉的数据结构题2
查看>>