箭头函数没有自己的this和arguments,它里面的this和arguments都是他所在的父作用域的this和arguments
// 箭头函数// function inc (number) {// return number + 1// }// 最简方式// const inc = n => n + 1// 完整参数列表,函数体多条语句,返回值仍需 returnconst inc = (n, m) => {console.log('inc invoked')return n + 1}console.log(inc(100))const arr = [1, 2, 3, 4, 5, 6, 7]// arr.filter(function (item) {// return item % 2// })// 常用场景,回调函数arr.filter(i => i % 2)
箭头函数与 this
// 箭头函数不会改变 this 指向// TODO 箭头函数与 thisconst person = {name: 'tom',// sayHi: function () {// console.log(`hi, my name is ${this.name}`) // hi, my name is tom// },sayHi: () => {console.log(`hi, my name is ${this.name}`) // hi, my name is undefined},sayHiAsync: function () {// const _this = this// setTimeout(function () {// console.log(_this.name)// }, 1000)console.log(this) // { name: 'tom', sayHi: [Function: sayHi], sayHiAsync: [Function: sayHiAsync] }setTimeout(() => {// console.log(this.name)console.log(this) // 同外面this}, 1000)}}person.sayHi()person.sayHiAsync()
