ES6 极简教程(ES6 Tutorial) 文 / 东海陈光剑
ES6 極簡(jiǎn)教程(ES6 Tutorial)
文 / 東海陳光劍
ECMAScript簡(jiǎn)介
JavaScript是ECMAScript的實(shí)現(xiàn)和擴(kuò)展,由ECMA(一個(gè)類似W3C的標(biāo)準(zhǔn)組織)參與進(jìn)行標(biāo)準(zhǔn)化。ECMAScript定義了:
- 語言語法 – 語法解析規(guī)則、關(guān)鍵字、語句、聲明、運(yùn)算符等。
- 類型 – 布爾型、數(shù)字、字符串、對(duì)象等。
- 原型和繼承
- 內(nèi)建對(duì)象和函數(shù)的標(biāo)準(zhǔn)庫 – JSON、Math、數(shù)組方法、對(duì)象自省方法等。
ECMAScript標(biāo)準(zhǔn)不定義HTML或CSS的相關(guān)功能,也不定義類似DOM(文檔對(duì)象模型)的Web API,這些都在獨(dú)立的標(biāo)準(zhǔn)中進(jìn)行定義。ECMAScript涵蓋了各種環(huán)境中JS的使用場(chǎng)景,無論是瀏覽器環(huán)境還是類似node.js的非瀏覽器環(huán)境。
版本號(hào)6
- ECMAScript標(biāo)準(zhǔn)的歷史版本分別是1、2、3、5。
那么為什么沒有第4版?其實(shí),在過去確實(shí)曾計(jì)劃發(fā)布提出巨量新特性的第4版,但最終卻因想法太過激進(jìn)而慘遭廢除(這一版標(biāo)準(zhǔn)中曾經(jīng)有一個(gè)極其復(fù)雜的支持泛型和類型推斷的內(nèi)建靜態(tài)類型系統(tǒng))。
ES4飽受爭(zhēng)議,當(dāng)標(biāo)準(zhǔn)委員會(huì)最終停止開發(fā)ES4時(shí),其成員同意發(fā)布一個(gè)相對(duì)謙和的ES5版本,隨后繼續(xù)制定一些更具實(shí)質(zhì)性的新特性。這一明確的協(xié)商協(xié)議最終命名為“Harmony”,因此,ES5規(guī)范中包含這樣兩句話:
ECMAScript是一門充滿活力的語言,并在不斷進(jìn)化中。
未來版本的規(guī)范中將持續(xù)進(jìn)行重要的技術(shù)改進(jìn)。
ES5
- 2009年發(fā)布的改進(jìn)版本ES5,引入了Object.create()、Object.defineProperty()、getters和setters、嚴(yán)格模式以及JSON對(duì)象。常用的數(shù)組方法:.map()、. filter()這些。
ES6
- 箭頭函數(shù)(arrow functions)
- 字符串插值(string interpolation)
- 代理(proxies)
- 生成器(generators)
- 類
- 模塊
TypeScript
- 相對(duì)于ES6,TypeScript最大的改善是增加了類型系統(tǒng)(Type System)。
- ES5, ES6, TypeScript 發(fā)展關(guān)系
const and let
const (val)
- const is a new keyword in ES6 for declaring variables. const is more powerful than var. Once used, the variable can’t be reassigned. In other words, it’s an immutable variable except when it used with objects.
- 怎樣使用
- This is really useful for targeting the selectors. For example, when we have a single button that fires an event, or when you want to select an HTML element in JavaScript, use const instead of var. This is because var is ‘hoisted’. It’s always preferable to use const when don’t want to reassign the variable .
let (var)
- let can be reassigned and take new value. It creates a mutable variable.
let is the same as const in that both are blocked-scope. It means that the variable is only available within its scope.
- 怎樣使用
- This is really useful for targeting the selectors. For example, when we have a single button that fires an event, or when you want to select an HTML element in JavaScript, use const instead of var. This is because var is ‘hoisted’. It’s always preferable to use const when don’t want to reassign the variable .
Arrow functions ()=>{}
The arrow function seems more readable and clean! You won’t need to use the old syntax anymore.
Also, you can use Arrow function with map, filter, and reduce built-in functions. With ES6 you can write shorter and smarter code. You can use the same with filter and reduce.
The arrow function is really awesome, and makes your code more readable, more structured, and look like modern code. Instead of using this:
怎樣使用
* // 在 Node 中使用模塊的正確姿勢(shì): const log = require("./lib/util_for_node");// ES5 fun function helloES5(name) {return 'Hello,' + name; }log(helloES5('ES5'));// ES6 arrow fun const helloES6 = (name) => {return `Hello,${name}` }; log(helloES6('ES6'));// ORconst helloES6Simple = name => `Hello,${name}`; log(helloES6Simple('ES6Simple'));輸出:
$ node es6_arrow_fun_demo.jsHello,ES5Hello,ES6Hello,ES6Simple- As you see, the arrow function seems more readable and clean! You won’t need to use the old syntax anymore.
Also, you can use Arrow function with map, filter, and reduce built-in functions.
* // 在 Node 中使用模塊的正確姿勢(shì): const log = require("./lib/util_for_node");const plArray = ['Java', 'Kotlin', 'JavaScript', 'Python', 'Go'];// ES5 funvar iter = plArray.map(function (e) {return 'Hi,' + e; })log(iter);// ES6 arrow fun const iterArrow = plArray.map(e => `Hi, ${e}`) log(iterArrow);/*** The map function with arrows looks more clear and readable than map in ES5.* With ES6 you can write shorter and smarter code.* You can use the same with filter and reduce.*/輸出:
$ node es6_arrow_fun_using_map_demo.js[ 'Hi,Java', 'Hi,Kotlin', 'Hi,JavaScript', 'Hi,Python', 'Hi,Go' ][ 'Hi, Java','Hi, Kotlin','Hi, JavaScript','Hi, Python','Hi, Go' ]參考資料:http://es6-features.org/#Lexicalthis
Template Literals
是什么
- Template literals or template strings are pretty cool. We don’t have to use the plus (+) operator to concatenate strings, or when we want to use a variable inside a string.
怎樣使用
* // 在 Node 中使用模塊的正確姿勢(shì): const log = require("./lib/util_for_node");// ES5 string plus function helloES5(name, age) {return 'Hello,' + name + ', My Age is ' + age; }log(helloES5('ES5', 10));// ES6 template literals const helloES6 = (name, age) => {return `Hello,${name}, My Age is ${age}` }; log(helloES6('ES6', 5));/** 輸出:$ node es6_template_literals_demo.jsHello,ES5, My Age is 10Hello,ES6, My Age is 5*/- So simple! It’s a really huge difference between the old syntax and ES6. When playing with strings, the literal string in ES6 looks more organized and well structured than ES5.
Default parameters
閑話休敘,直接上代碼
const log = require("./lib/util_for_node");// ES5 function helloES5(name, age) {return 'Hello,' + name + ', My Age is ' + age; }log(helloES5('ES5'));// ES6 const helloES6 = (name, age = 10) => { // default age is 10return `Hello,${name}, My Age is ${age}` }; log(helloES6('ES6')); // age is not set , will be default 10/** 輸出:$ node es6_default_params_demo.jsHello,ES5, My Age is undefinedHello,ES6, My Age is 10*/Array and object destructing
What is it ?
- Destruction makes the assignment of the values of an array or object to the new variable easier.
實(shí)操
* const log = require('./lib/util_for_node')// ES5 var pl = {name: 'Kotlin',typeSystem: 'Static Type',platform: 'JVM,JS,Android,Native' }var name = pl.name var typeSystem = pl.typeSystem var platform = pl.platform log(name) log(typeSystem) log(platform)const scope = () => { // avoid 上面的 var 變量聲明的作用域沖突// ES6const pll = {name: 'Kotlin',typeSystem: 'Static Type',platform: 'JVM,JS,Android,Native'}let {name, typeSystem, platform} = pll // destructinglog(name)log(typeSystem)log(platform) }scope()With ES5, we have to assign each value to each variable. With ES6, we just put our values within curly brackets to get any property of the object.
Note: if you assign a variable that is not identical to the name of property, it will return undefined. For example, if the name of the property is name and we assign it to a username variable, it will return undefined.
We always have to name the variable the same as the name of the property. But in case we want to rename the variable, we can use the colon : instead.
// For the array, we use the same syntax as the object. We have just to replace the curly brackets with square brackets.
const plArray = ['Kotlin', 'Java', 'JavaScript', 'Scala', 'Python', 'Lisp'] // array let [v1, v2, v3, v4, v5, v6] = plArray // Attention: here is [] log(v1) log(v2) log(v3) log(v4) log(v5) log(v6)Import and export
What is it ?
- Using import and export in your JavaScript application makes it more powerful. They allow you to create separate and reusable components.
If you are familiar with any JavaScript MVC framework, you will see that they use import and export to handle the components most of the time. So how do they really work?
It is simple! export allows you to export a module to be used in another JavaScript component. We use import to import that module to use it in our component.
If we want to import more than one module, we just put them within curly brackets.
Node中使用 import/export :
參考:《Node.js 中使用 ES6 中的 import / export 的方法大全》
Promises
是什么
new Promise(function(resolve, reject) {if(true) { resolve() };if(false) { reject() }; })- Promise對(duì)象有三種狀態(tài),他們分別是:
pending: 等待中,或者進(jìn)行中,表示還沒有得到結(jié)果
resolved(Fulfilled): 已經(jīng)完成,表示得到了我們想要的結(jié)果,可以繼續(xù)往下執(zhí)行
rejected: 也表示得到結(jié)果,但是由于結(jié)果并非我們所愿,因此拒絕執(zhí)行
這三種狀態(tài)不受外界影響,而且狀態(tài)只能從pending改變?yōu)閞esolved或者rejected,并且不可逆。在Promise對(duì)象的構(gòu)造函數(shù)中,將一個(gè)函數(shù)作為第一個(gè)參數(shù)。而這個(gè)函數(shù),就是用來處理Promise的狀態(tài)變化。
resolve函數(shù)的作用是,將Promise對(duì)象的狀態(tài)從“未完成”變?yōu)椤俺晒Α?#xff08;即從 pending 變?yōu)?resolved),在異步操作成功時(shí)調(diào)用,并將異步操作的結(jié)果,作為參數(shù)傳遞出去;
reject函數(shù)的作用是,將Promise對(duì)象的狀態(tài)從“未完成”變?yōu)椤笆 ?#xff08;即從 pending 變?yōu)?rejected),在異步操作失敗時(shí)調(diào)用,并將異步操作報(bào)出的錯(cuò)誤,作為參數(shù)傳遞出去。
Promise 實(shí)例生成以后,可以用then 方法分別指定resolved狀態(tài)和rejected狀態(tài)的回調(diào)函數(shù)。
- Promise 的含義
Promise 是異步編程的一種解決方案,比傳統(tǒng)的解決方案–回調(diào)函數(shù)和事件--更合理和更強(qiáng)大。它由社區(qū)最早提出和實(shí)現(xiàn),ES6將其寫進(jìn)了語言標(biāo)準(zhǔn),統(tǒng)一了語法,原生提供了Promise
所謂Promise ,簡(jiǎn)單說就是一個(gè)容器,里面保存著某個(gè)未來才回結(jié)束的事件(通常是一個(gè)異步操作)的結(jié)果。從語法上說,Promise是一個(gè)對(duì)象,從它可以獲取異步操作的消息。
Promise 對(duì)象的狀態(tài)不受外界影響
三種狀態(tài):
pending:進(jìn)行中
fulfilled :已經(jīng)成功
rejected 已經(jīng)失敗
狀態(tài)改變:
Promise對(duì)象的狀態(tài)改變,只有兩種可能:
從pending變?yōu)閒ulfilled
從pending變?yōu)閞ejected。
這兩種情況只要發(fā)生,狀態(tài)就凝固了,不會(huì)再變了,這時(shí)就稱為resolved(已定型)
Rest parameter and Spread operator
- The rest parameters are used to get the argument of an array, and return a new array.
- The spread operator has the same syntax as the rest parameter, but the spread operator takes the Array itself and not just the arguments. We can use the Spread parameter to get the values of an Array, instead of using a for loop or any other method.
代碼實(shí)操
const log = require('./lib/util_for_node')const plArray = ['Kotlin', 'Java', 'JavaScript', 'Scala', 'Python', 'Lisp'] const [v1, v2, v3, ...rest] = plArray log(rest)// 擴(kuò)展運(yùn)算符( spread )是三個(gè)點(diǎn)(...)。它好比 rest 參數(shù)的逆運(yùn)算,將一個(gè)數(shù)組轉(zhuǎn)為用逗號(hào)分隔的參數(shù)序列。
let spread = (...arr) => {console.log(arr)return arr }spread(plArray)console.log(...[1, 2, 3]) // 1 2 3 console.log(1, ...[2, 3, 4], 5) // 1 2 3 4 5log(...[1, 2, 3]) // 這里用 log()函數(shù)有問題,會(huì)輸出 1 // 1 2 3 log(1, ...[2, 3, 4], 5) // 這里用 log()函數(shù)有問題,會(huì)輸出 1 // 1 2 3 4 5/**$ node es6_rest_parameter_and_spread_operator.js[ 'Scala', 'Python', 'Lisp' ][ [ 'Kotlin', 'Java', 'JavaScript', 'Scala', 'Python', 'Lisp' ] ]1 2 31 2 3 4 5*/Class of OOP
Classes
- Classes are the core of object oriented programming (OOP). They make your code more secure and encapsulated. Using classes gives your code a nice structure and keeps it oriented.
Code實(shí)例講解
類的聲明與構(gòu)造
// 在 Node 中使用模塊的正確姿勢(shì): const log = require("./lib/util_for_node");class Product {constructor(name, price) {this.name = namethis.price = price}list() {return [new Product("iPad Pro 2018", 10000),new Product('iPhone XMax', 9000)]} }const main = () => {const p = new Product()const list = p.list()log(list) }main();/*** 輸出:$ node es6_class_demo.js[ Product { name: 'iPad Pro 2018', price: 10000 },Product { name: 'iPhone XMax', price: 9000 } ]*/- 繼承 extends
源代碼:
https://github.com/AK-47-D/nodejs_es6_tutorials
文章可視化大綱:
ES6 極簡(jiǎn)教程(ES6 Tutorial) .pngKotlin 開發(fā)者社區(qū)
國(guó)內(nèi)第一Kotlin 開發(fā)者社區(qū)公眾號(hào),主要分享、交流 Kotlin 編程語言、Spring Boot、Android、React.js/Node.js、函數(shù)式編程、編程思想等相關(guān)主題。
開發(fā)者社區(qū) QRCode.jpg總結(jié)
以上是生活随笔為你收集整理的ES6 极简教程(ES6 Tutorial) 文 / 东海陈光剑的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 美丽小猪Java基础笔记02【小美女程序
- 下一篇: 【面试题】【ES6】let和const命