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. 直接作为事件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. this:用function生成的函数会定义一个自己的this,而箭头函数没有自己的this,而是会和上一层的作用域共享this。

  2. apply & call:由于箭头函数已经绑定了this的值,即使使用apply或者call也不能只能起到传参数的作用,并不能强行改变箭头函数里的this。

  3. arguments:普通函数里arguments代表了调用时传入的参数,但是箭头函数不然,箭头函数会把arguments当成一个普通的变量,顺着作用域链由内而外地查询。

  4. 不能被new:箭头函数不能与new关键字一起使用,会报错。

  5. typeof运算符和普通的function一样:

    var func = a => a
    console.log(typeof func); // "function"
  6. instanceof也返回true,表明也是Function的实例:

    console.log(func instanceof Function); // true
       
原文地址:https://www.cnblogs.com/daiwenru/p/7083870.html