使用一些我喜欢的东西开始使用ES6

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/394597.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

A 子类继承父类,子类的构造函数会覆盖父类的构造函数

//子类 没有定义 构造 函数时&#xff0c;默认继承父类的构造方法&#xff1a;输出结果为 Class A... // 子类 定义了 构造 函数时&#xff0c;就不会继承父类的构造方法&#xff1a;输出结果是 Class B... <?php class A{ public function __construct(){ echo &qu…

fifo算法_缓存算法FIFO、LFU、LRU

阅读文本大概需要3分钟。0x01&#xff1a;FIFO算法FIFO(First in First out)&#xff0c;先进先出。其实在操作系统的设计理念中很多地方都利用到了先进先出的思想&#xff0c;比如作业调度(先来先服务)&#xff0c;为什么这个原则在很多地方都会用到呢&#xff1f;因为这个原则…

Pile 0009: Vim命令梳理

正常模式&#xff08;按Esc或Ctrl[进入&#xff09; 左下角显示文件名或为空插入模式&#xff08;按i键进入&#xff09; 左下角显示--INSERT--可视模式&#xff08;按v键进入&#xff09; 左下角显示--VISUAL-- i 在当前位置生前插入 I 在当前行首插入 a 在当前位置后插入 A 在…

Introduction of Version Control/Git, SVN

Introduction of Version Control/Git, SVN 什么是版本控制&#xff1f; 你可以把一个版本控制系统&#xff08;缩写VCS&#xff09;理解为一个“数据库”&#xff0c;在需要的时候&#xff0c;它可以帮你完整地保存一个项目的快照。当你需要查看一个之前的快照&#xff08;称之…

怎样设置计算机远程桌面,电脑如何设置远程连接,手把手教你如何远程

说起远程桌面很多用户都认为是从WIN2000 SERVER才开始引入的&#xff0c;实际上我们可以在WIN98甚至是DOS中看到他的身影。远程桌面采用的是一种类似TELNET的技术&#xff0c;他是从TELNET协议发展而来的。那么如何设置自动开机&#xff0c;下面&#xff0c;我们就来看看如何设…

查看这些有用的ECMAScript 2015(ES6)提示和技巧

by rajaraodv通过rajaraodv 查看这些有用的ECMAScript 2015(ES6)提示和技巧 (Check out these useful ECMAScript 2015 (ES6) tips and tricks) EcmaScript 2015 (aka ES6) has been around for couple of years now, and various new features can be used in clever ways. I…

inputstream转fileinputstream对象_FileInputStream类:文件字节输入流

API ----IO ----字节输入输出流练习 java.lang.Object 继承者 java.io.InputStream 继承者 java.io.FileInputStreampublic FileInputStream类速查速记&#xff1a;直接包装File用于从记事本中读数据 in是针对java来说的&#xff0c;从记事本读入到java* 构造方法&#xff1a;…

IBM将推NVMe存储解决方案

先前&#xff0c;IBM曾对外宣称将开发新的NVMe解决方案&#xff0c;并推动行业参与者进一步探索新协议&#xff0c;以支持更快的数据传输。周日&#xff0c;IBM表示新的语言协议——NVMe&#xff08;非易失性存储器&#xff09;正在逐步取代SAS和SATA等旧有的固态硬盘存储标准。…

html5中3个盒子怎样设置,Web前端开发任务驱动式教程(HTML5+CSS3+JavaScript)任务10 盒子模型及应用.pptx...

第五单元 盒子模型任务10 盒子模型及应用学习目标盒子模型的概念掌握边框的设置内边距的设置外边距的设置学习目标了解:利用盒子模型布局网页的优势任务目标实战演练——制作古诗文欣赏网页强化训练——制作散文赏析网页知识准备1. 盒子模型的概念知识准备1. 盒子模型的概念CSS…

SQL手工注入入门级笔记(更新中)

一、字符型注入 针对如下php代码进行注入&#xff1a; $sql"select user_name from users where name$_GET[name]"; 正常访问URL:http://url/xxx.php?nameadmin 此时实际数据库语句: select user_name from users where nameadmin 利用以上结果可想到SQL注入构造语句…

materialize_使用Materialize快速介绍材料设计

materialize什么是材料设计&#xff1f; (What is Material Design?) Material Design is a design language created by Google. According to material.io, Material Design aims to combine:Material Design是Google创建的一种设计语言。 根据material.io &#xff0c;Mate…

python处理完数据导入数据库_python 将execl测试数据导入数据库操作

import xlrd import pymysql # 打开execl表 book xlrd.open_workbook(XXXX测试用例.xlsx) sheet book.sheet_by_name(Sheet1) # print(sheet.nrows) # 创建mysql连接 conn pymysql.connect( host127.0.0.1, userroot, password123456, dbdemo1, port3306, charsetutf8 ) # 获…

增删改查类

<?php // 所有数据表的基类 abstract class Model {protected $tableName "";protected $pdo "";protected $sql"";function __construct() {$pdo new PDO( "mysql:host" . DB_HOST . ";dbname" . DB_NAME, DB_USERN…

html网页和cgi程序编程,CGI 编程方式学习

1.大家都知道CGI是通用网关接口&#xff0c;可以用来编写动态网页。而且CGI可以用很多种语言来写&#xff0c;用perl来编写最常见&#xff0c;我这里就是用perl来编写做例子。讲到编写CGI编程方式&#xff0c;编写CGI有两程编程风格。(1)功能型编程(function-oriented style)这…

20175305张天钰 《java程序设计》第四周课下测试总结

第四周课下测试总结 错题 某方法在父类的访问权限是public&#xff0c;则子类重写时级别可以是protected。 A .true B .false 正确答案&#xff1a;B 解析&#xff1a;书P122&#xff1a;子类不允许降低方法的访问权限&#xff0c;但可以提高访问权限。 复杂题&#xff08;易错…

强化学习q学习求最值_通过Q学习更深入地学习强化学习

强化学习q学习求最值by Thomas Simonini通过托马斯西蒙尼(Thomas Simonini) 通过Q学习更深入地学习强化学习 (Diving deeper into Reinforcement Learning with Q-Learning) This article is part of Deep Reinforcement Learning Course with Tensorflow ?️. Check the syl…

BZOJ 1113: [Poi2008]海报PLA

1113: [Poi2008]海报PLA Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 1025 Solved: 679[Submit][Status][Discuss]Description N个矩形,排成一排. 现在希望用尽量少的矩形海报Cover住它们. Input 第一行给出数字N,代表有N个矩形.N在[1,250000] 下面N行,每行给出矩形的长…

Python自动化运维之常用模块—OS

os模块的作用&#xff1a;  os&#xff0c;语义为操作系统&#xff0c;所以肯定就是操作系统相关的功能了&#xff0c;可以处理文件和目录这些我们日常手动需要做的操作&#xff0c;就比如说&#xff1a;显示当前目录下所有文件/删除某个文件/获取文件大小……  另外&#…

opengl三维图形图形颜色_【图形学基础】基本概念

右手坐标系。类似OpenGL遵循的右手坐标系&#xff1a;首先它是三维的笛卡尔坐标系&#xff1a;原点在屏幕正中&#xff0c;x轴从屏幕左向右&#xff0c;最左是-1&#xff0c;最右是1&#xff1b;y轴从屏幕下向上&#xff0c;最下是-1&#xff0c;最上是1&#xff1b;z轴从屏幕里…

xp职称计算机考试题库,2015年职称计算机考试XP题库.doc

2015年职称计算机考试XP题库.doc (7页)本资源提供全文预览&#xff0c;点击全文预览即可全文预览,如果喜欢文档就下载吧&#xff0c;查找使用更方便哦&#xff01;9.90 积分&#xfeff;2015年职称计算机考试XP题库职称计算机考试考点精编&#xff1a;工具栏的设置与操作XP中将…