knockkey总结 1.0 箭头函数没有
this, 它的this是通过作用域链查到外层作用域的this, 且指向函数定义时的this而非执行时
1.1 不能用call/apply/bind修改this指向, 但可以通过修改外层作用域的this来间接修改
- 不可以用作构造函数, 不能使用
new命令, 否则会报错 - 箭头函数没有
arguments对象, 如果要用, 使用rest参数代替 - 不可以使用
yield命令, 因此箭头函数不能用作Generator函数 - 箭头函数没有
prototype属性 - 不适用于动态上下文中的回调函数
const btn1 = document.getElementById('btn1')
const btn2 = document.getElementById('btn2')
btn1.addEventListener('click', () => {
console.log(this === window);
this.innerHTML = 'clicked'
})
btn2.addEventListener('click', function () {
console.log(this === window);
this.innerHTML = 'clicked'
})
- 不适用于Vue声明周期和method
data(){return {name:'谭'}}
methods:{
getName:()=>{
//报错 Cannot read properties of undefined (reading 'name')
return this.name
},
getName(){
return this.name //正常
}
},
mounted:() => {
//报错 Cannot read properties of undefined (reading 'name')
console.log('msg',this.name)
},
mounted(){
console.log('msg',this.name)//正常
}