【九月打卡】第1天 哪些地方不能用箭頭函數
课程名称:2周刷完100道前端优质面试真题
课程章节:第四章第八节
主讲老师:双越
课程内容概述
一.箭头函数有什么缺点?
二.什么时候不能用箭头函数?
缺点:
没有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 } }
6.React中可以使用箭头函数
原因:
Vue本质上是一个js对象
React它本质上是一个ES6 Class
class Foo{ constructor(name,city){ this.name = name; this.city = city; } getName = () =>{ return this.name; } } const f = new Foo('双越',‘北京’); console.log(f.getName()); //双越
重点:
要熟练应用箭头函数,也要对函数this arguments敏感
传统vue组件是JS对象,传统React组件是class,两者不同
點擊查看更多內容
1人點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦