使用一些我喜歡的東西開始使用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.pswp.cn/news/394597.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394597.shtml
英文地址,請注明出處:http://en.pswp.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中將…