箭头函数有哪些缺点?
- 没有arguments
- 无法通过apply/call/bind来改变this
- 某些箭头函数代码难以阅读
哪些地方不能使用箭头函数?
-
对象方法
const obj = { name:"双越", getName: ()=>{ return this.name; }} console.log(obj.getName) //获取不到内容
2.原型方法
const obj = { name:"双越"}obj.__proto__.getName = () =>{ return this.name;}console.log(obj.getName()) //获取不到内容
3.构造函数
const Fn4 = (name,city)=>{ this.name = name; this.city = city; }const f = new Fn4('双越',‘北京’)console.log(f); //报错Fn4 is not a constructor
4.动态上下文中的回调函数
const btn1 = document.getElementById('btn1');btn1.addEventListener('click',()=>{ this.innerHTML = 'clicked'; //this获取不到内容,因此会报错})
5.vue生命周期和method
{ data(){ return { name: "双越" } }, methods: { getName: ()=>{ //报错 cannot read properties of undefined(reading name) return this.name; } getName(){ return this.name; } } mounted:()=>{ console.log(this.name); //拿不到this }}
特别补充:
React中可以使用箭头函数
原因:Vue本质上是一个js对象;React本质上是一个ES6 Class
要熟练使用箭头函数,同时也要对this arguments极其敏感.