箭頭函數
- 寫法
ES5:
var show = function(){
console.log('es5')
}
ES6箭頭函數:
let show = ()=>{
console.log('es5');
}
- 唯且僅有只有一個參數的時候()可以省略
let show = a => {
console.log(a);
}
- 當只有return一行的時候,可以省略return,{}
let add = (a,b)=>a+b
this指向需要注意:es5,是誰調用this,this指向誰;es6中,不管誰調用this,this指向定義他的對象
rest
- 對於參數不定的函數
ES5:
function show(){
console.log(arguments);
}
arguments是偽數組,轉化為數組,Array.from(arguments)或者Array.prototype.slice.apply(arguments),將他轉化數組
ES6:
function show(...arg){
console.log(arg);//arg是一個數組
}
es5中argument改變可以改變傳入的參數的值,反之,亦然,而用了...arg的方法中,argument改變還是傳入值改變,都不會影響互相
- ...運算符還可以用來展開數組
let arr = [1,2]
let add = (a,b)=>a+b
add(...arr); //3
...運算符不能直接用來做復制操作,否則會報錯
函數值默認
function show(a,b=1,c=2){
console.log(a+b+c);
}
show(0); //3
show(0,2) //4
show(0,2,3) //5
