在es6中更新了不少函數的特性。其中在開發經常使用的有參數默認值,不定參數,展開運算符和箭頭函數等。git
在es5函數的默認值是用||
實現:es6
function func(url, timeout, cb) {
timeout = timeout || 2000;
cb = cb || function() {};
console.log(url, timeout, cb);
}
func('a.com'); // a.com 2000 function() {}
func('b.com', 0); // b.com 2000 function() {}
複製代碼
這種方式能夠看出若是參數傳遞一個轉爲boolean
值爲false
的狀況都會用默認值。除非在函數裏面判斷參數是否爲undefiend
再使用默認值。github
在es6中,能夠直接在參數列表直接用=
賦值方式定義默認值:數組
function func(url, timeout = 2000, cb = function() {}) {
console.log(url, timeout, cb);
}
func('a.com'); // a.com 2000 function() {}
func('b.com', 0); // b.com 0 function() {}
複製代碼
上面的代碼在不傳或者傳入undefiend時
才使用默認值。app
默認值可使用函數調用的方式。當函數調用是纔會執行參數的默認值函數,聲明是不執行:函數
let value = 5;
function getValue() {
return value++;
}
function add(a, b = getValue()) {
return a + b;
}
console.log(add(1)); // 6
console.log(add(1)); // 7
console.log(add(1, 2)); // 3
複製代碼
默認值容許使用左邊先聲明的參數變量,不容許使用後面的參數,由於此時處於臨時死區。post
function getValue(value) {
return value;
}
function add(a, b = getValue(a)) {
return a + b;
}
console.log(add(1)); // 2
console.log(add(1, 2)); // 3
複製代碼
當函數調用當參數比聲明時多,要訪問聲明的參數能夠遍歷arguments
。在es6中,提供剩餘參數這一特性,用...args
表示,args表示多餘參數的數組:ui
function func(a, ...args) {
console.log(args); // [2,3]
return args.reduce((pre, cur) => pre + cur, a);
}
console.log(func(1, 2, 3));
複製代碼
剩餘參數必須是最後一個參數,而且不容許在對象的set
函數使用,由於set
函數只能傳遞一個參數。this
function func(a, ...args, b) {
console.log(args);
}
console.log(func(1, 2, 3)); // Rest parameter must be last formal parameter
複製代碼
若是咱們須要把一個數組每一個元素做爲函數調用的參數,在es5中能夠用apply
方式調用:url
const arr = [1, 2, 3];
console.log(Math.max.apply(Math, arr)); // 3
複製代碼
在es6中利用開展運算符能夠更方便調用。展開運算符用...
符號對一個數組拆散,做爲函數的參數:
const arr = [1, 2, 3];
// 能夠在其餘參數共用
console.log(Math.max(...arr, 0)); // 3
複製代碼
在es6引入的一種新的定義函數的方式,基本用法:
// 無參數
const func = () => {};
// 單個參數省略括號
const funcA = a => a;
// 多個參數
const funcB = (a, b) => a + b;
// 多條語句用{}包括函數體
const funcC = (a, b) => {
b++;
return a + b;
};
// 返回對象
const funcD = () => ({ a: 1 });
複製代碼
沒有this綁定。在箭頭函數中無this對象,它的值爲最近一個不是箭頭函數的this。
let obj = {
name: 'wozien',
show: function() {
return () => {
// 這裏的this就是調用show函數的this
console.log(this.name);
};
}
};
obj.show()();
複製代碼
不能做爲new調用。 箭頭函數沒有函數內部屬性[[Constructor]]
,因此沒法做爲構造函數。
const Person = name => {
this.name = name;
};
new Person('wozien'); // TypeError: Person is not a constructor
複製代碼
沒有arguments參數。取值和this相似:
function func(a) {
return () => {
console.log(arguments[0]);
};
}
func(1)(); // 1
複製代碼
沒法經過call和apply改變this指向,可是能夠執行函數。
let obj = {
name: 'wozien'
};
const show = () => {
console.log(this.name);
};
show.call(obj); // undefined
複製代碼
總而言之,箭頭函數只是看成是普通函數一種簡寫方式,在大部分場景都適用,好比在一個對象內綁定回調函數,並且回調函數用到該對象的屬性等,這是回調函數就能夠用箭頭函數定義。
咱們不建議箭頭函數做爲對象方法的定義,由於這違背了咱們在方法中使用對象屬性的初衷。
let obj = {
name: 'wozien',
show: () => {
console.log(this.name);
}
};
obj.show(); // undefined
複製代碼