ES6 箭头函数(Arrow Functions)

ES6 箭头函数(Arrow Functions)

ES6 可以使用 “箭头”(=>)定义函数,注意是函数,不要使用这种方式定义类(构造器)。

一、语法

  1. 具有一个参数的简单函数

    var single = a => a
    single('hello, world') // 'hello, world'
    
  2. 多个参数需要用到小括号,参数间逗号间隔,例如两个数字相加

    var add = (a, b) => a + b
    add(3, 8) // 11
    
  3. 函数体多条语句需要用到大括号

    var add = (a, b) => {
        if (typeof a == 'number' && typeof b == 'number') {
            return a + b
        } else {
            return 0
        }
    }
    
  4. 返回对象时需要用小括号包起来,因为大括号被占用解释为代码块了

    var getHash = arr => {
        // ...
        return ({
            name: 'Jack',
            age: 33
        })
    }
    
  5. 直接作为事件 handler

    document.addEventListener('click', ev => {
    console.log(ev)
    })
    
  6. 作为数组排序回调

    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 => a
    console.log(typeof func); // "function"
    
  2. instanceof 也返回 true,表明也是 Function 的实例

    console.log(func instanceof Function); 
    
  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。

  1. 箭头函数不能用 new.

    var Person = (name, age) => {
            this.name = name
            this.age = age
        }
        var p = new Func('John', 33) // error
    
  2. 不能使用 argument

    var func = () => {
        console.log(arguments)
    }
    func(55)
    
原文地址:https://www.cnblogs.com/liuyishi/p/9417783.html