js-哪些场景不适合箭头函数

由于箭头函数的 this 在定义时确定, 所以有一些地方不能用箭头函数

  1. 不能定义对象上的方法
1
2
3
4
5
6
7
8
let obj = {
a: 1,
func: () => {
console.log(this.a);
},
};
var a = 0;
obj.func(); // 0
  1. 不能定义动态上下文的回调函数
1
2
3
4
const btn = document.getElementById("id");
btn.addEventListener("click", () => {
console.log(this === window); // => true
});
  1. 不能作为构造函数
1
2
3
4
5
const Mes = (a) => {
this.a = a;
};
const kk = new Mes("hh");
// Throws "TypeError: Message is not a constructor"