1. 程式人生 > >JavaScript ES6 規範

JavaScript ES6 規範

ES6 簡介
ECMAScript 6 簡稱 ES6,是 JavaScript 語言的下一代標準,已經在2015年6月正式釋出了。它的目標是使得 JavaScript 語言可以用來編寫複雜的大型應用程式,成為企業級開發語言。

ECMAScript 和 JavaScript 的關係:前者是後者的語法規格,後者是前者的一種實現

Babel:將ES6程式碼轉為ES5程式碼 http://babeljs.io/

image
image

新特性
let、const
let 定義的變數不會被變數提升,const 定義的常量不能被修改,let 和 const 都是塊級作用域

ES6前,js 是沒有塊級作用域 {} 的概念的。(有函式作用域、全域性作用域、eval作用域)

ES6後,let 和 const 的出現,js 也有了塊級作用域的概念,前端的知識是日新月異的~

變數提升:在ES6以前,var關鍵字宣告變數。無論宣告在何處,都會被視為宣告在函式的最頂部;不在函式內即在全域性作用域的最頂部。這樣就會引起一些誤解。例如:

console.log(a); // undefined
var a = ‘hello’;

上面的程式碼相當於

var a;
console.log(a);
a = ‘hello’;

而 let 就不會被變數提升

console.log(a); // a is not defined
let a = ‘hello’;
const 定義的常量不能被修改

var name = “bai”;
name = “ming”;
console.log(name); // ming

const name = “bai”;
name = “ming”; // Assignment to constant variable.
console.log(name);
import、export
import匯入模組、export匯出模組

// 全部匯入
import people from ‘./example’

// 將整個模組當作單一物件進行匯入,該模組的所有匯出都會作為物件的屬性存在
import * as example from “./example.js”
console.log(

example.name)
console.log(example.getName())

// 匯入部分,引入非 default 時,使用花括號
import {name, age} from ‘./example’

// 匯出預設, 有且只有一個預設
export default App

// 部分匯出
export class App extend Component {};
class、extends、super
ES5中最令人頭疼的的幾個部分:原型、建構函式,繼承,有了ES6我們不再煩惱!

ES6引入了Class(類)這個概念。

class Animal {
constructor() {
this.type = ‘animal’;
}
says(say) {
console.log(this.type + ’ says ’ + say);
}
}

let animal = new Animal();
animal.says(‘hello’); //animal says hello

class Cat extends Animal {
constructor() {
super();
this.type = ‘cat’;
}
}

let cat = new Cat();
cat.says(‘hello’); //cat says hello
上面程式碼首先用class定義了一個“類”,可以看到裡面有一個constructor方法,這就是構造方法,而this關鍵字則代表例項物件。簡單地說,constructor內定義的方法和屬性是例項物件自己的,而constructor外定義的方法和屬性則是所有實力物件可以共享的。

Class之間可以通過extends關鍵字實現繼承,這比ES5的通過修改原型鏈實現繼承,要清晰和方便很多。上面定義了一個Cat類,該類通過extends關鍵字,繼承了Animal類的所有屬性和方法。

super關鍵字,它指代父類的例項(即父類的this物件)。子類必須在constructor方法中呼叫super方法,否則新建例項時會報錯。這是因為子類沒有自己的this物件,而是繼承父類的this物件,然後對其進行加工。如果不呼叫super方法,子類就得不到this物件。

ES6的繼承機制,實質是先創造父類的例項物件this(所以必須先呼叫super方法),然後再用子類的建構函式修改this。

// ES5
var Shape = function(id, x, y) {
this.id = id,
this.move(x, y);
};
Shape.prototype.move = function(x, y) {
this.x = x;
this.y = y;
};

var Rectangle = function id(ix, x, y, width, height) {
Shape.call(this, id, x, y);
this.width = width;
this.height = height;
};
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var Circle = function(id, x, y, radius) {
Shape.call(this, id, x, y);
this.radius = radius;
};
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;

// ES6
class Shape {
constructor(id, x, y) {
this.id = id this.move(x, y);
}
move(x, y) {
this.x = x this.y = y;
}
}

class Rectangle extends Shape {
constructor(id, x, y, width, height) {
super(id, x, y) this.width = width this.height = height;
}
}

class Circle extends Shape {
constructor(id, x, y, radius) {
super(id, x, y) this.radius = radius;
}
}
arrow functions (箭頭函式)
函式的快捷寫法。不需要 function 關鍵字來建立函式,省略 return 關鍵字,繼承當前上下文的 this 關鍵字

// ES5
var arr1 = [1, 2, 3];
var newArr1 = arr1.map(function(x) {
return x + 1;
});

// ES6
let arr2 = [1, 2, 3];
let newArr2 = arr2.map((x) => {
x + 1
});
箭頭函式小細節:當你的函式有且僅有一個引數的時候,是可以省略掉括號的;當你函式中有且僅有一個表示式的時候可以省略{}

let arr2 = [1, 2, 3];
let newArr2 = arr2.map(x => x + 1);
JavaScript語言的this物件一直是一個令人頭痛的問題,執行上面的程式碼會報錯,這是因為setTimeout中的this指向的是全域性物件。

class Animal {
constructor() {
this.type = ‘animal’;
}
says(say) {
setTimeout(function() {
console.log(this.type + ’ says ’ + say);
}, 1000);
}
}

var animal = new Animal();
animal.says(‘hi’); //undefined says hi
解決辦法:

// 傳統方法1: 將this傳給self,再用self來指代this
says(say) {
var self = this;
setTimeout(function() {
console.log(self.type + ’ says ’ + say);
}, 1000);
}

// 傳統方法2: 用bind(this),即
says(say) {
setTimeout(function() {
console.log(this.type + ’ says ’ + say);
}.bind(this), 1000);
}

// ES6: 箭頭函式
// 當我們使用箭頭函式時,函式體內的this物件,就是定義時所在的物件
says(say) {
setTimeout(() => {
console.log(this.type + ’ says ’ + say);
}, 1000);
}
template string (模板字串)
解決了 ES5 在字串功能上的痛點。

第一個用途:字串拼接。將表示式嵌入字串中進行拼接,用 和${}來界定。

// es5
var name1 = “bai”;
console.log(‘hello’ + name1);

// es6
const name2 = “ming”;
console.log(hello${name2});
第二個用途:在ES5時我們通過反斜槓來做多行字串拼接。ES6反引號 `` 直接搞定。

// es5
var msg = “Hi
man!”;

// es6
const template = `


hello world

`; 另外:includes repeat

// includes:判斷是否包含然後直接返回布林值
let str = ‘hahah’;
console.log(str.includes(‘y’)); // false

// repeat: 獲取字串重複n次
let s = ‘he’;
console.log(s.repeat(3)); // ‘hehehe’
destructuring (解構)
簡化陣列和物件中資訊的提取。

ES6前,我們一個一個獲取物件資訊;

ES6後,解構能讓我們從物件或者數組裡取出資料存為變數

// ES5
var people1 = {
name: ‘bai’,
age: 20,
color: [‘red’, ‘blue’]
};

var myName = people1.name;
var myAge = people1.age;
var myColor = people1.color[0];
console.log(myName + ‘----’ + myAge + ‘----’ + myColor);

// ES6
let people2 = {
name: ‘ming’,
age: 20,
color: [‘red’, ‘blue’]
}

let { name, age } = people2;
let [first, second] = people2.color;
console.log(${name}----${age}----${first});
default 函式預設引數

// ES5 給函式定義引數預設值
function foo(num) {
num = num || 200;
return num;
}

// ES6
function foo(num = 200) {
return num;
}
rest arguments (rest引數)
解決了 es5 複雜的 arguments 問題

function foo(x, y, …rest) {
return ((x + y) * rest.length);
}
foo(1, 2, ‘hello’, true, 7); // 9
Spread Operator (展開運算子)
第一個用途:組裝陣列

let color = [‘red’, ‘yellow’];
let colorful = […color, ‘green’, ‘blue’];
console.log(colorful); // [“red”, “yellow”, “green”, “blue”]
第二個用途:獲取陣列除了某幾項的其他項

let num = [1, 3, 5, 7, 9];
let [first, second, …rest] = num;
console.log(rest); // [5, 7, 9]
物件
物件初始化簡寫

// ES5
function people(name, age) {
return {
name: name,
age: age
};
}

// ES6
function people(name, age) {
return {
name,
age
};
}
物件字面量簡寫(省略冒號與 function 關鍵字)

// ES5
var people1 = {
name: ‘bai’,
getName: function () {
console.log(this.name);
}
};

// ES6
let people2 = {
name: ‘bai’,
getName () {
console.log(this.name);
}
};
另外:Object.assign()

ES6 物件提供了Object.assign()這個方法來實現淺複製。Object.assign()可以把任意多個源物件自身可列舉的屬性拷貝給目標物件,然後返回目標物件。第一引數即為目標物件。在實際專案中,我們為了不改變源物件。一般會把目標物件傳為{}

const obj = Object.assign({}, objA, objB)

// 給物件新增屬性
this.seller = Object.assign({}, this.seller, response.data)
Promise
用同步的方式去寫非同步程式碼

// 發起非同步請求
fetch(’/api/todos’)
.then(res => res.json())
.then(data => ({
data
}))
.catch(err => ({
err
}));
Generators
生成器( generator)是能返回一個迭代器的函式。

生成器函式也是一種函式,最直觀的表現就是比普通的function多了個星號*,在其函式體內可以使用yield關鍵字,有意思的是函式會在每個yield後暫停。

這裡生活中有一個比較形象的例子。咱們到銀行辦理業務時候都得向大廳的機器取一張排隊號。你拿到你的排隊號,機器並不會自動為你再出下一張票。也就是說取票機“暫停”住了,直到下一個人再次喚起才會繼續吐票。

迭代器:當你呼叫一個generator時,它將返回一個迭代器物件。這個迭代器物件擁有一個叫做next的方法來幫助你重啟generator函式並得到下一個值。next方法不僅返回值,它返回的物件具有兩個屬性:done和value。value是你獲得的值,done用來表明你的generator是否已經停止提供值。繼續用剛剛取票的例子,每張排隊號就是這裡的value,列印票的紙是否用完就這是這裡的done。

// 生成器
function *createIterator() {
yield 1;
yield 2;
yield 3;
}

// 生成器能像正規函式那樣被呼叫,但會返回一個迭代器
let iterator = createIterator();

console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2
console.log(iterator.next().value); // 3
迭代器對非同步程式設計作用很大,非同步呼叫對於我們來說是很困難的事,我們的函式並不會等待非同步呼叫完再執行,你可能會想到用回撥函式,(當然還有其他方案比如Promise比如Async/await)。

生成器可以讓我們的程式碼進行等待。就不用巢狀的回撥函式。使用generator可以確保當非同步呼叫在我們的generator函式執行一下行程式碼之前完成時暫停函式的執行。

那麼問題來了,咱們也不能手動一直呼叫next()方法,你需要一個能夠呼叫生成器並啟動迭代器的方法。就像這樣子的:

function run(taskDef) {
// taskDef 即一個生成器函式
// 建立迭代器,讓它在別處可用
let task = taskDef();

// 啟動任務
let result = task.next();

// 遞迴使用函式來保持對 next() 的呼叫
function step() {
// 如果還有更多要做的
if (!result.done) {
result = task.next();
step();
}
}

// 開始處理過程
step();
}
總結
以上就是 ES6 最常用的一些語法,可以說這20%的語法,在ES6的日常使用中佔了80%