箭頭函數(Arrow Function)
目錄:
語法
單一參數的單行箭頭函數
用法:arg => statement
const fn = foo => `${foo} hello`; // means retuen `foo + 'hello'`
常用於簡單的處理函數,比如過濾:
let array = ['a', 'bc', 'def', 'ghij'];
array = array.filter(item => item.length >= 2); // bc, def, ghij
多參數的單行箭頭函數
用法:(arg1, arg2) => statement
const fn = (foo, bar) => foo + bar
常用於數組的處理,如排序:
let array = ['a', 'bc', 'def', 'ghij'];
array = array.sort((a, b) => a.length < b.length); // ghij, def, bc, a
多行箭頭函數
用法:args.. => {statement}
foo => {
return 'hello world';
}
(foo, bar) => {
return foo + bar;
}
無參數箭頭函數
用法:() => statement
const greet = () => 'hello world';
this 穿透
箭頭函數用於將函數內部的 this 延伸至上一層作用域中,即上一層的上下文會穿透到內層的箭頭函數中。
const obj = {
hello: 'world',
foo() {
// this
const bar = () => this.hello;
return bar;
}
}
window.hello = 'ES';
window.bar = obj.foo();
window.bar(); // 'world'
程序邏輯注意事項
箭頭函數對上下文的綁定是強制性的,無法通過apply或call方法改變。
const a = {
init(){
this.bar = () => this.dam
},
dam: 'hei',
foo(){
return this.dam;
}
}
const b = {
dam: 'ha'
}
a.init();
console.log(a.foo()); // hei
console.log(a.foo.bind(b).call(a)); //ha
console.log(a.bar.call(b)); //hei
不能隨意在頂層作用域使用箭頭函數。
// 假設當前運行環境爲瀏覽器,則頂層上下文爲“window”
const obj = {
msg: 'pong',
ping: () => this.msg // Warning!
}
obj.ping(); // undfined
var msg = 'bang!';
obj.ping(); // bang!
上面代碼的等價代碼:
var that = this;
var obj = {
//...
ping: function(){
retuen that.msg; // Warning
}
}
// 又等價爲
var that = this;
var obj = { /* ... */ };
obj.ping = function(){
return that.msg;
}
同樣地,在箭頭函數中也沒有arguments、 callee 甚至 caller 等對象。
const fn = () =>{
console.log(arguments);
}
fn(1, 2); // ReferenceError: arguments is not defined
//事實上輸出了{ i: 0, l: false, exports: {} }
若有使用 arguments 的需求,可以使用後續參數來獲取參數列表。
const fn = (...args) =>{
console.log(args[0]);
}
fn(1, 2); // 1
編寫語法注意事項
在使用單行箭頭函數時,請不要對單行的函數體做任何換行。
參數列表的右括弧、箭頭需要保持在同一行內。
單行箭頭函數只能包含一條語句,但如果是錯誤拋出語句(throw)等非表達式的語句,則需要使用花括號包裹。
const fn = x => {throw new Error('some error message')};
若要使用單行箭頭函數直接返回一個對象字面量,請使用一個括號包裹該對象字面量,而不是直接使用大括號,否則 ECMAScript 解析引擎會將其解析爲一個多行箭頭函數。
const ids = [1, 2, 3];
const users = ids.map(id => {id: id});
// 錯誤: [undefined, undefined, undefined]
const users = ids.map(id => ({id: id}));
// 正確: [{id: 1}, {id: 2}, {id: 3}]