ES6 簡介
ECMAScript 6 簡稱 ES6,是 JavaScript 語言的下一代標準,已經(jīng)在2015年6月正式發(fā)布了。它的目標是使得 JavaScript 語言可以用來編寫復(fù)雜的大型應(yīng)用程序,成為企業(yè)級開發(fā)語言。
ECMAScript 和 JavaScript 的關(guān)系:前者是后者的語法規(guī)格,后者是前者的一種實現(xiàn)
Babel:將ES6代碼轉(zhuǎn)為ES5代碼 http://babeljs.io/

新特性
let、const
let 定義的變量不會被變量提升,const 定義的常量不能被修改,let 和 const 都是塊級作用域
ES6前,js 是沒有塊級作用域 {} 的概念的。(有函數(shù)作用域、全局作用域、eval作用域)
ES6后,let 和 const 的出現(xiàn),js 也有了塊級作用域的概念,前端的知識是日新月異的~
變量提升:在ES6以前,var關(guān)鍵字聲明變量。無論聲明在何處,都會被視為聲明在函數(shù)的最頂部;不在函數(shù)內(nèi)即在全局作用域的最頂部。這樣就會引起一些誤解。例如:
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導(dǎo)入模塊、export導(dǎo)出模塊
// 全部導(dǎo)入
import people from './example'
// 將整個模塊當作單一對象進行導(dǎo)入,該模塊的所有導(dǎo)出都會作為對象的屬性存在
import * as example from "./example.js"
console.log(example.name)
console.log(example.getName())
// 導(dǎo)入部分,引入非 default 時,使用花括號
import {name, age} from './example'
// 導(dǎo)出默認, 有且只有一個默認
export default App
// 部分導(dǎo)出
export class App extend Component {};
class、extends、super
ES5中最令人頭疼的的幾個部分:原型、構(gòu)造函數(shù),繼承,有了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方法,這就是構(gòu)造方法,而this關(guān)鍵字則代表實例對象。簡單地說,constructor內(nèi)定義的方法和屬性是實例對象自己的,而constructor外定義的方法和屬性則是所有實力對象可以共享的。
Class之間可以通過extends關(guān)鍵字實現(xiàn)繼承,這比ES5的通過修改原型鏈實現(xiàn)繼承,要清晰和方便很多。上面定義了一個Cat類,該類通過extends關(guān)鍵字,繼承了Animal類的所有屬性和方法。
super關(guān)鍵字,它指代父類的實例(即父類的this對象)。子類必須在constructor方法中調(diào)用super方法,否則新建實例時會報錯。這是因為子類沒有自己的this對象,而是繼承父類的this對象,然后對其進行加工。如果不調(diào)用super方法,子類就得不到this對象。
ES6的繼承機制,實質(zhì)是先創(chuàng)造父類的實例對象this(所以必須先調(diào)用super方法),然后再用子類的構(gòu)造函數(shù)修改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 (箭頭函數(shù))
函數(shù)的快捷寫法。不需要 function 關(guān)鍵字來創(chuàng)建函數(shù),省略 return 關(guān)鍵字,繼承當前上下文的 this 關(guān)鍵字
// 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
});
箭頭函數(shù)小細節(jié):當你的函數(shù)有且僅有一個參數(shù)的時候,是可以省略掉括號的;當你函數(shù)中有且僅有一個表達式的時候可以省略{}
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
解決辦法:
// 傳統(tǒng)方法1: 將this傳給self,再用self來指代this
says(say) {
var self = this;
setTimeout(function() {
console.log(self.type + ' says ' + say);
}, 1000);
}
// 傳統(tǒng)方法2: 用bind(this),即
says(say) {
setTimeout(function() {
console.log(this.type + ' says ' + say);
}.bind(this), 1000);
}
// ES6: 箭頭函數(shù)
// 當我們使用箭頭函數(shù)時,函數(shù)體內(nèi)的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 = `<div>
<span>hello world</span>
</div>`;
另外:includes repeat
// includes:判斷是否包含然后直接返回布爾值
let str = 'hahah';
console.log(str.includes('y')); // false
// repeat: 獲取字符串重復(fù)n次
let s = 'he';
console.log(s.repeat(3)); // 'hehehe'
destructuring (解構(gòu))
簡化數(shù)組和對象中信息的提取。
ES6前,我們一個一個獲取對象信息;
ES6后,解構(gòu)能讓我們從對象或者數(shù)組里取出數(shù)據(jù)存為變量
// 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 函數(shù)默認參數(shù)
// ES5 給函數(shù)定義參數(shù)默認值
function foo(num) {
num = num || 200;
return num;
}
// ES6
function foo(num = 200) {
return num;
}
rest arguments (rest參數(shù))
解決了 es5 復(fù)雜的 arguments 問題
function foo(x, y, ...rest) {
return ((x + y) * rest.length);
}
foo(1, 2, 'hello', true, 7); // 9
Spread Operator (展開運算符)
第一個用途:組裝數(shù)組
let color = ['red', 'yellow'];
let colorful = [...color, 'green', 'blue'];
console.log(colorful); // ["red", "yellow", "green", "blue"]
第二個用途:獲取數(shù)組除了某幾項的其他項
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 關(guān)鍵字)
// 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()這個方法來實現(xiàn)淺復(fù)制。Object.assign()可以把任意多個源對象自身可枚舉的屬性拷貝給目標對象,然后返回目標對象。第一參數(shù)即為目標對象。在實際項目中,我們?yōu)榱瞬桓淖冊磳ο蟆R话銜涯繕藢ο髠鳛閧}
const obj = Object.assign({}, objA, objB)
// 給對象添加屬性
this.seller = Object.assign({}, this.seller, response.data)
Promise
用同步的方式去寫異步代碼
// 發(fā)起異步請求
fetch('/api/todos')
.then(res => res.json())
.then(data => ({
data
}))
.catch(err => ({
err
}));
Generators
生成器( generator)是能返回一個迭代器的函數(shù)。
生成器函數(shù)也是一種函數(shù),最直觀的表現(xiàn)就是比普通的function多了個星號*,在其函數(shù)體內(nèi)可以使用yield關(guān)鍵字,有意思的是函數(shù)會在每個yield后暫停。
這里生活中有一個比較形象的例子。咱們到銀行辦理業(yè)務(wù)時候都得向大廳的機器取一張排隊號。你拿到你的排隊號,機器并不會自動為你再出下一張票。也就是說取票機“暫?!弊×?,直到下一個人再次喚起才會繼續(xù)吐票。
迭代器:當你調(diào)用一個generator時,它將返回一個迭代器對象。這個迭代器對象擁有一個叫做next的方法來幫助你重啟generator函數(shù)并得到下一個值。next方法不僅返回值,它返回的對象具有兩個屬性:done和value。value是你獲得的值,done用來表明你的generator是否已經(jīng)停止提供值。繼續(xù)用剛剛?cè)∑钡睦?,每張排隊號就是這里的value,打印票的紙是否用完就這是這里的done。
// 生成器
function *createIterator() {
yield 1;
yield 2;
yield 3;
}
// 生成器能像正規(guī)函數(shù)那樣被調(diào)用,但會返回一個迭代器
let iterator = createIterator();
console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2
console.log(iterator.next().value); // 3
迭代器對異步編程作用很大,異步調(diào)用對于我們來說是很困難的事,我們的函數(shù)并不會等待異步調(diào)用完再執(zhí)行,你可能會想到用回調(diào)函數(shù),(當然還有其他方案比如Promise比如Async/await)。
生成器可以讓我們的代碼進行等待。就不用嵌套的回調(diào)函數(shù)。使用generator可以確保當異步調(diào)用在我們的generator函數(shù)運行一下行代碼之前完成時暫停函數(shù)的執(zhí)行。
那么問題來了,咱們也不能手動一直調(diào)用next()方法,你需要一個能夠調(diào)用生成器并啟動迭代器的方法。就像這樣子的:
function run(taskDef) {
// taskDef 即一個生成器函數(shù)
// 創(chuàng)建迭代器,讓它在別處可用
let task = taskDef();
// 啟動任務(wù)
let result = task.next();
// 遞歸使用函數(shù)來保持對 next() 的調(diào)用
function step() {
// 如果還有更多要做的
if (!result.done) {
result = task.next();
step();
}
}
// 開始處理過程
step();
}
總結(jié)
以上就是 ES6 最常用的一些語法,可以說這20%的語法,在ES6的日常使用中占了80%
最后更新時間:2017-06-24 18:52:48
原始文章鏈接:http://bxm0927.github.io/2017/06/24/es6_study/