es6中最常用的當(dāng)屬箭頭函數(shù)
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}
除了上面的簡潔的寫法以外,es6對于this的指向問題也發(fā)生了變化,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
由于定時器的調(diào)用,this的指向發(fā)生變換,(定時器的調(diào)用需要把里面的事件加載到異步執(zhí)行的序列當(dāng)中,當(dāng)執(zhí)行完代碼,this的質(zhì)就指向的是window,這里我們需要強制綁定一下this的指向,主要的方法有下面兩種)
1.第一種是將this傳值給self,再用self來代替this
says(say){
var self = this;
setTimeout(function(){
console.log(self.type + ' says ' + say)
}, 1000)
第二種使用bind(this)來綁定this的指向
says(say){
setTimeout(function(){
console.log(this.type + ' says ' + say)
}.bind(this), 1000)
現(xiàn)在我們可以使用箭頭函數(shù)而不用處理thisd指向問題
class Animal {
constructor(){
this.type = 'animal'
}
says(say){
setTimeout( () => {
console.log(this.type + ' says ' + say) //this的指向就是他的上下文對象就是實力話出來的animal對象
}, 1000)
}
}
var animal = new Animal()
animal.says('hi') //animal says hi
當(dāng)我們使用箭頭函數(shù)時,函數(shù)體內(nèi)的this對象,就是定義時所在的對象,而不是使用時所在的對象。
并不是因為箭頭函數(shù)內(nèi)部有綁定this的機制,實際原因是箭頭函數(shù)根本沒有自己的this,它的this是繼承外面的,因此內(nèi)部的this就是外層代碼塊的this。
template string 模板字符串
這個東西也是非常有用,當(dāng)我們要插入大段的html內(nèi)容到文檔中時,傳統(tǒng)的寫法非常麻煩,所以之前我們通常會引用一些模板工具庫,比如mustache等等
傳統(tǒng)的寫法
$("#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!
`);
用反引號(\)來標(biāo)識起始,用${}`來引用變量,
destructuring
es6允許按照一定的模式,從數(shù)組和對象中提取值,對變量進(jìn)行賦值
最常用的是數(shù)組和對象的解構(gòu)
ea6中的模塊化
假設(shè)我們有兩個js文件: index.js和content.js,現(xiàn)在我們想要在index.js中使用content.js返回的結(jié)果,我們要怎么做呢?
//content.js
export default 'A cat'
//index.js
import animal from './content'
//index.js
import { say, type } from './content'
let says = say()
console.log(`The ${type} says ${says}`) //The dog says Hello
這里輸入的時候要注意:大括號里面的變量名,必須與被導(dǎo)入模塊(content.js)對外接口的名稱相同。
終極秘籍
考慮下面的場景:上面的content.js一共輸出了三個變量(default, say, type),假如我們的實際項目當(dāng)中只需要用到type這一個變量,其余兩個我們暫時不需要。我們可以只輸入一個變量:
import { type } from './content'
由于其他兩個變量沒有被使用,我們希望代碼打包的時候也忽略它們,拋棄它們,這樣在大項目中可以顯著減少文件的體積。
ES6幫我們實現(xiàn)了!