let, const
const的定義是不可重新賦值的值,不同于不可變的值;const定義的Object,在定以后仍可修改屬性。
使用場景很廣,包括常量,配置項,以及引用的組件,定義的大部分中間變量等
項目中的一些例子:
const unSubscribe = $ngRedux.connect(state => {
return {
noNoVictim: noVictim.id.indexOf(state.session.id) > -1
}
}, {})($scope)
const LZString = require('lz-string')
模板字符串
模板字符串中除了可以使用變量,也可以使用函數返回值,對象的屬性等;
const start = 'hi all'
const getName = ()=> {
return 'mochase'
}
const conf = {
fav: 'commic'
}
const msg = `${start}, my name is ${getName()}, ${conf.fav} is my favourite`
對象簡寫
const config = {
//指定原型對象
_proto_: basicConfig,
//屬性簡寫
bookNum,
//方法簡寫
getBookNum (){
return this.bookNum
}
}
箭頭函數
箭頭函數沒有獨立執行上下文(this),所以其內部引用的this對象會直接訪問父級
在未使用箭頭函數前,我們在過程函數中使用父級 this,需要將其顯式緩存到另一個中間變量中,因為過程函數有獨立的 this變量,會覆蓋父級;
箭頭函數不但沒有獨立 this,他也沒有獨立的 arguments,所以如果需要取不定參的時候,要么使用 function,要么用 ES6 的另一個新特性 rest(具體在 rest 中會有詳解)
解構
//解構可以設置默認值
const {book1, book3 = 'not find'} = bookCollection()
//解構時可以取到指定對象的任何屬性,包括它包含的方法
const {length: setLength} = bookSet //setLength = bookSet.length = 3
擴展運算符...
rest + spread
//rest得到的是一個真正的數組而不是一個偽數組
const getOptions= function(...args){
console.log(args.join) //function
}
Promise
多個異步任務同時執行用promise.all, 順序執行用鏈式調用
//Promise.all
Promise
.all([jsBuildPromise, cssBuildPromise])
.then(() => {
....
})
//chain
jsBuildPromise
.then(()=> cssBuildPromise)
.then(() => {
....
})