DIV CSS 佈局教程網

ES6 箭頭函數(Arrow Functions)語法與注意事項全整理
編輯:JavaScript基礎知識     

ES6 用「箭頭」=> 來定義函數。切記:它定義的是函數,不要拿來定義類或構造器。

一、語法形式

1. 單參數可省略括號

var single = a => a;
single('hello, world'); // 'hello, world'

2. 無參數時括號不能省

var log = () => { alert('no param'); };

3. 多參數必須用括號包裹,以逗號分隔

var add = (a, b) => a + b;
add(3, 8); // 11

4. 函數體有多條語句時加大括號

var add = (a, b) => {
  if (typeof a == 'number' && typeof b == 'number') {
    return a + b;
  } else {
    return 0;
  }
};

5. 返回對象字面量時要用小括號包起來,否則大括號會被當成代碼塊解析。

var getHash = arr => {
  // ...
  return ({ name: 'Jack', age: 33 });
};

6. 直接當作事件處理器

document.addEventListener('click', ev => {
  console.log(ev);
});

7. 作為數組排序回調

var arr = [1, 9, 2, 4, 3, 8].sort((a, b) => {
  if (a - b > 0) {
    return 1;
  } else {
    return -1;
  }
});
arr; // [1, 2, 3, 4, 8, 9]

二、需要注意的幾點

1. typeof 的結果與普通函數一致

var func = a => a;
console.log(typeof func); // "function"

2. instanceof Function 同樣為 true,說明它也是 Function 的實例。

console.log(func instanceof Function); // true

3. this 指向固定,取決於定義時所在的上下文,不會在調用時被重新綁定。

obj = {
  data: ['John Backus', 'John Hopcroft'],
  init: function () {
    document.onclick = ev => {
      alert(this.data); // ['John Backus', 'John Hopcroft']
    };
    // 對比:普通函數的 this 會指向被綁定的元素
    // document.onclick = function (ev) {
    //   alert(this.data); // undefined
    // }
  }
};
obj.init();

這特性很實用,從此不必再寫 me、self、_this 這類臨時變量,也不用到處 bind。

4. 不能作為構造函數配合 new 使用

var Person = (name, age) => {
  this.name = name;
  this.age = age;
};
var p = new Person('John', 33); // TypeError

5. 沒有自己的 arguments 對象

var func = () => {
  console.log(arguments);
};
func(55);

補充一點:在 Firefox 36 中測試時上面這段仍能輸出 55,看起來當時的實現並未完全遵循這條限制。

三、小結

箭頭函數讓匿名回調的書寫大幅精簡,尤其是 this 的詞法綁定,省掉了大量綁定噪音。但正因為它沒有自己的 this、arguments,也不能當構造器,物件方法、需要動態 this 的場合仍然應該使用傳統函數表達式。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved