ES6箭頭函數

來源:互聯網
上載者:User

標籤:被佔用   handle   blog   define   list   pos   error   不用   elf   

【轉】ES6箭頭函數(Arrow Functions)

ES6可以使用“箭頭”(=>)定義函數,注意是函數,不要使用這種方式定義類(構造器)。

 

一、文法

1. 具有一個參數的簡單函數

var single = a => asingle(‘hello, world‘) // ‘hello, world‘

  

2. 沒有參數的需要用在箭頭前加上小括弧

var log = () => {    alert(‘no param‘)}

  

3. 多個參數需要用到小括弧,參數間逗號間隔,例如兩個數字相加

var add = (a, b) => a + badd(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. 直接作為事件handler

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運算子和普通的function一樣

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

  

2. instanceof也返回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‘]        }        // 非箭頭函數        // 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 Func(‘John‘, 33) // error

  

5. 不能使用argument

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

  

對於5,在Firefox36裡測試是可以輸出55的,貌似並沒有這個限制

 

相關:

http://kangax.github.io/compat-table/es6/

 

ES6箭頭函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.