ES6 极简教程(ES6 Tutorial) 文 / 东海陈光剑
ES6 極簡教程(ES6 Tutorial)
文 / 東海陳光劍
ECMAScript簡介
JavaScript是ECMAScript的實現和擴展,由ECMA(一個類似W3C的標準組織)參與進行標準化。ECMAScript定義了:
- 語言語法 – 語法解析規則、關鍵字、語句、聲明、運算符等。
- 類型 – 布爾型、數字、字符串、對象等。
- 原型和繼承
- 內建對象和函數的標準庫 – JSON、Math、數組方法、對象自省方法等。
ECMAScript標準不定義HTML或CSS的相關功能,也不定義類似DOM(文檔對象模型)的Web API,這些都在獨立的標準中進行定義。ECMAScript涵蓋了各種環境中JS的使用場景,無論是瀏覽器環境還是類似node.js的非瀏覽器環境。
版本號6
- ECMAScript標準的歷史版本分別是1、2、3、5。
那么為什么沒有第4版?其實,在過去確實曾計劃發布提出巨量新特性的第4版,但最終卻因想法太過激進而慘遭廢除(這一版標準中曾經有一個極其復雜的支持泛型和類型推斷的內建靜態類型系統)。
ES4飽受爭議,當標準委員會最終停止開發ES4時,其成員同意發布一個相對謙和的ES5版本,隨后繼續制定一些更具實質性的新特性。這一明確的協商協議最終命名為“Harmony”,因此,ES5規范中包含這樣兩句話:
ECMAScript是一門充滿活力的語言,并在不斷進化中。
未來版本的規范中將持續進行重要的技術改進。
ES5
- 2009年發布的改進版本ES5,引入了Object.create()、Object.defineProperty()、getters和setters、嚴格模式以及JSON對象。常用的數組方法:.map()、. filter()這些。
ES6
- 箭頭函數(arrow functions)
- 字符串插值(string interpolation)
- 代理(proxies)
- 生成器(generators)
- 類
- 模塊
TypeScript
- 相對于ES6,TypeScript最大的改善是增加了類型系統(Type System)。
- ES5, ES6, TypeScript 發展關系
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 中使用模塊的正確姿勢: 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 中使用模塊的正確姿勢: 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 中使用模塊的正確姿勢: 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.
實操
* 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對象有三種狀態,他們分別是:
pending: 等待中,或者進行中,表示還沒有得到結果
resolved(Fulfilled): 已經完成,表示得到了我們想要的結果,可以繼續往下執行
rejected: 也表示得到結果,但是由于結果并非我們所愿,因此拒絕執行
這三種狀態不受外界影響,而且狀態只能從pending改變為resolved或者rejected,并且不可逆。在Promise對象的構造函數中,將一個函數作為第一個參數。而這個函數,就是用來處理Promise的狀態變化。
resolve函數的作用是,將Promise對象的狀態從“未完成”變為“成功”(即從 pending 變為 resolved),在異步操作成功時調用,并將異步操作的結果,作為參數傳遞出去;
reject函數的作用是,將Promise對象的狀態從“未完成”變為“失敗”(即從 pending 變為 rejected),在異步操作失敗時調用,并將異步操作報出的錯誤,作為參數傳遞出去。
Promise 實例生成以后,可以用then 方法分別指定resolved狀態和rejected狀態的回調函數。
- Promise 的含義
Promise 是異步編程的一種解決方案,比傳統的解決方案–回調函數和事件--更合理和更強大。它由社區最早提出和實現,ES6將其寫進了語言標準,統一了語法,原生提供了Promise
所謂Promise ,簡單說就是一個容器,里面保存著某個未來才回結束的事件(通常是一個異步操作)的結果。從語法上說,Promise是一個對象,從它可以獲取異步操作的消息。
Promise 對象的狀態不受外界影響
三種狀態:
pending:進行中
fulfilled :已經成功
rejected 已經失敗
狀態改變:
Promise對象的狀態改變,只有兩種可能:
從pending變為fulfilled
從pending變為rejected。
這兩種情況只要發生,狀態就凝固了,不會再變了,這時就稱為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.
代碼實操
const log = require('./lib/util_for_node')const plArray = ['Kotlin', 'Java', 'JavaScript', 'Scala', 'Python', 'Lisp'] const [v1, v2, v3, ...rest] = plArray log(rest)// 擴展運算符( spread )是三個點(...)。它好比 rest 參數的逆運算,將一個數組轉為用逗號分隔的參數序列。
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()函數有問題,會輸出 1 // 1 2 3 log(1, ...[2, 3, 4], 5) // 這里用 log()函數有問題,會輸出 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實例講解
類的聲明與構造
// 在 Node 中使用模塊的正確姿勢: 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 極簡教程(ES6 Tutorial) .pngKotlin 開發者社區
國內第一Kotlin 開發者社區公眾號,主要分享、交流 Kotlin 編程語言、Spring Boot、Android、React.js/Node.js、函數式編程、編程思想等相關主題。
開發者社區 QRCode.jpg總結
以上是生活随笔為你收集整理的ES6 极简教程(ES6 Tutorial) 文 / 东海陈光剑的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 美丽小猪Java基础笔记02【小美女程序
- 下一篇: Python-Django毕业设计基于的