Skip to content
On this page

箭头函数

在 ES6 的语法中还提供了箭头函语法,让我们在代码书写时就能确定 this 的指向(编译时绑定)

javascript
const obj = {
  sayThis: () => {
    console.log(this);
  },
};

obj.sayThis(); // window 因为 JavaScript 没有块作用域,所以在定义 sayThis 的时候,里面的 this 就绑到 window 上去了
const globalSay = obj.sayThis;
globalSay(); // window 浏览器中的 global 对象
1
2
3
4
5
6
7
8
9

虽然箭头函数的 this 能够在编译的时候就确定了 this 的指向,但也需要注意一些潜在的坑

下面举个例子:

绑定事件监听

javascript
const button = document.getElementById("mngb");
button.addEventListener("click", () => {
  console.log(this === window); // true
  this.innerHTML = "clicked button";
});
1
2
3
4
5

上述可以看到,我们其实是想要 this 为点击的 button,但此时 this 指向了 window

包括在原型上添加方法时候,此时 this 指向 window

javascript
Cat.prototype.sayName = () => {
  console.log(this === window); //true
  return this.name;
};
const cat = new Cat("mm");
cat.sayName();
1
2
3
4
5
6

同样的,箭头函数不能作为构建函数

沪ICP备20006251号-1