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(() => {
....
})