參考鏈接:
http://www.jianshu.com/p/ebfeb687eb70
http://www.cnblogs.com/Wayou/p/es6_new_features.html
1.let, const
這兩個的用途與var
類似,都是用來聲明變量的,但在實際運用中他倆都有各自的特殊用途。
1.1第一種場景就是你現在看到的內層變量覆蓋外層變量
var name = 'zach' while (true) { var name = 'obama' console.log(name) //obama break } console.log(name) //obama
使用var
兩次輸出都是obama,這是因為ES5只有全局作用域和函數作用域,沒有塊級作用域。
而let
則實際上為JavaScript新增了塊級作用域。用它所聲明的變量,只在let
命令所在的代碼塊內有效。
let name = 'zach' while (true) { let name = 'obama' console.log(name) //obama break } console.log(name) //zach
1.2var
帶來的第二個不合理場景就是用來計數的循環變量泄露為全局變量
var a = []; for (var i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // 10
變量i是var聲明的,在全局范圍內都有效。所以每一次循環,新的i值都會覆蓋舊值,導致最后輸出的是最后一輪的i的值。而使用let則不會出現這個問題。
var a = []; for (let i = 0; i < 10; i++) { a[i] = function () { console.log(i); }; } a[6](); // 6
1.3const
也用來聲明變量,但是聲明的是常量。一旦聲明,常量的值就不能改變
const PI = Math.PI PI = 23 //Module build failed: SyntaxError: /es6/app.js: "PI" is read-only
當我們嘗試去改變用const聲明的常量時,瀏覽器就會報錯。
const有一個很好的應用場景,就是當我們引用第三方庫的時聲明的變量,用const來聲明可以避免未來不小心重命名而導致出現bug:
const monent = require('moment')
2.class, extends, super
ES6提供了更接近傳統語言的寫法,引入了Class(類)這個概念。新的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。
3.箭頭操作符
ES6中新增的箭頭操作符=>便有異曲同工之妙。它簡化了函數的書寫。操作符左邊為輸入的參數,而右邊則是進行的操作以及返回的值Inputs=>outputs
function(i){ return i + 1; } //ES5 (i) => i + 1 //ES6
如果方程比較復雜,則需要用{}
把代碼包起來:
function(x, y) { x++; y--; return x + y; } (x, y) => {x++; y--; return x+y}
除了看上去更簡潔以外,arrow function還有一項超級無敵的功能!
長期以來,JavaScript語言的this
對象一直是一個令人頭痛的問題,在對象方法中使用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
運行上面的代碼會報錯,這是因為setTimeout
中的this
指向的是全局對象。所以為了讓它能夠正確的運行,傳統的解決方法有兩種:
第一種是將this傳給self,再用self來指代this
says(say){ var self = this; setTimeout(function(){ console.log(self.type + ' says ' + say) }, 1000)
第二種方法是用bind(this)
,即
says(say){ setTimeout(function(){ console.log(self.type + ' says ' + say) }.bind(this), 1000)
但現在我們有了箭頭函數,就不需要這么麻煩了:
class Animal { constructor(){ this.type = 'animal' } says(say){ setTimeout( () => { console.log(this.type + ' says ' + say) }, 1000) } } var animal = new Animal() animal.says('hi') //animal says hi
當我們使用箭頭函數時,函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象。
並不是因為箭頭函數內部有綁定this的機制,實際原因是箭頭函數根本沒有自己的this,它的this是繼承外面的,因此內部的this就是外層代碼塊的this。
4.template string(字符串模板)
字符串模板相對簡單易懂些。
用反引號(`)
來標識起始,用${}
來引用變量,而且所有的空格和縮進都會被保留在輸出之中
//產生一個隨機數 var num=Math.random(); //將這個數字輸出到console console.log(`your num is ${num}`);
大家可以先看下面一段代碼:
$("#result").append( "There are <b>" + basket.count + "</b> " + "items in your basket, " + "<em>" + basket.onSale + "</em> are on sale!" );
我們要用一堆的'+'號來連接文本與變量,而使用ES6的新特性模板字符串``后,我們可以直接這么來寫:
$("#result").append(` There are <b>${basket.count}</b> items in your basket, <em>${basket.onSale}</em> are on sale! `);
5.destructuring
自動解析數組或對象中的值。
比如若一個函數要返回多個值,常規的做法是返回一個對象,將每個值做為這個對象的屬性返回。
let cat = 'ken' let dog = 'lili' let zoo = {cat: cat, dog: dog} console.log(zoo) //Object {cat: "ken", dog: "lili"}
但在ES6中,利用解構這一特性,可以直接返回一個數組,然后數組中的值會自動被解析到對應接收該值的變量中。
let cat = 'ken' let dog = 'lili' let zoo = {cat, dog} console.log(zoo) //Object {cat: "ken", dog: "lili"}
反過來可以這么寫:
let dog = {type: 'animal', many: 2} let { type, many} = dog console.log(type, many) //animal 2
var [x,y]=getVal(),//函數返回值的解構 [name,,age]=['wayou','male','secrect'];//數組解構 function getVal() { return [ 1, 2 ]; } console.log('x:'+x+', y:'+y);//輸出:x:1, y:2 console.log('name:'+name+', age:'+age);//輸出: name:wayou, age:secrect
6.default, rest
default很簡單,意思就是默認值。
調用animal()
方法時忘了傳參數,傳統的做法就是加上這一句type = type || 'cat'
來指定默認值。
function sayHello(name){ //傳統的指定默認參數的方式 var name=name||'dude'; console.log('Hello '+name); } //運用ES6的默認參數 function sayHello2(name='dude'){ console.log(`Hello ${name}`); } sayHello();//輸出:Hello dude sayHello('Wayou');//輸出:Hello Wayou sayHello2();//輸出:Hello dude sayHello2('Wayou');//輸出:Hello Wayou
不定參數是在函數中使用命名參數同時接收不定數量的未命名參數。這只是一種語法糖,在以前的JavaScript代碼中我們可以通過arguments變量來達到這一目的。不定參數的格式是三個句點后跟代表所有不定參數的變量名。比如下面這個例子中,…x代表了所有傳入add函數的參數。
//將所有參數相加的函數 function add(...x){ return x.reduce((m,n)=>m+n); } //傳遞任意個數的參數 console.log(add(1,2,3));//輸出:6 console.log(add(1,2,3,4,5));//輸出:15
拓展參數則是另一種形式的語法糖,它允許傳遞數組或者類數組直接做為函數的參數而不用通過apply。
var people=['Wayou','John','Sherlock']; //sayHello函數本來接收三個單獨的參數人妖,人二和人三 function sayHello(people1,people2,people3){ console.log(`Hello ${people1},${people2},${people3}`); } //但是我們將一個數組以拓展參數的形式傳遞,它能很好地映射到每個單獨的參數 sayHello(...people);//輸出:Hello Wayou,John,Sherlock //而在以前,如果需要傳遞數組當參數,我們需要使用函數的apply方法 sayHello.apply(null,people);//輸出:Hello Wayou,John,Sherlock