课程名称: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 constructor4.动态上下文中的回调函数
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,两者不同
随时随地看视频