Skip to content

箭头函数


JavaScript 充满了我们需要编写在其他地方执行的小函数的情况。

  • arr.forEach(func) —— forEach 对每个数组元素都执行 func
  • setTimeout(func) —— func 由内建调度器执行。

箭头函数没有this,如果访问 this,则会从外部获取。

javascript
let user = {
    name: 'dano',
    eat: ["apple", "peal"],
    showEat() {
        this.eat.forEach((value,index,array) => {
            console.log(this.name + " eat "+value);
        })
    }
}

user.showEat();

箭头函数的这种特性可以将其==视为外层函数的一部分==,箭头函数“的”this,就是外层函数的this。

  • 没有 this
  • 没有 arguments
  • 不能使用 new 调用,它没有this,无法将创建的空对象绑定到this上构造函数与New
  • 它们也没有 super,但目前我们还没有学到它。我们将在 类继承 一章中学习它。