箭头函数没有自己的this和arguments,它里面的this和arguments都是他所在的父作用域的this和arguments

    1. // 箭头函数
    2. // function inc (number) {
    3. // return number + 1
    4. // }
    5. // 最简方式
    6. // const inc = n => n + 1
    7. // 完整参数列表,函数体多条语句,返回值仍需 return
    8. const inc = (n, m) => {
    9. console.log('inc invoked')
    10. return n + 1
    11. }
    12. console.log(inc(100))
    13. const arr = [1, 2, 3, 4, 5, 6, 7]
    14. // arr.filter(function (item) {
    15. // return item % 2
    16. // })
    17. // 常用场景,回调函数
    18. arr.filter(i => i % 2)

    箭头函数与 this

    1. // 箭头函数不会改变 this 指向
    2. // TODO 箭头函数与 this
    3. const person = {
    4. name: 'tom',
    5. // sayHi: function () {
    6. // console.log(`hi, my name is ${this.name}`) // hi, my name is tom
    7. // },
    8. sayHi: () => {
    9. console.log(`hi, my name is ${this.name}`) // hi, my name is undefined
    10. },
    11. sayHiAsync: function () {
    12. // const _this = this
    13. // setTimeout(function () {
    14. // console.log(_this.name)
    15. // }, 1000)
    16. console.log(this) // { name: 'tom', sayHi: [Function: sayHi], sayHiAsync: [Function: sayHiAsync] }
    17. setTimeout(() => {
    18. // console.log(this.name)
    19. console.log(this) // 同外面this
    20. }, 1000)
    21. }
    22. }
    23. person.sayHi()
    24. person.sayHiAsync()