使用箭头函数注意点:
- 箭头函数内的this对象就是定义时所在的对象,不是使用时所在的对象
- 箭头函数不可以当作构造函数,不可以使用new命令。
- 箭头函数不可以使用arguments对象,该对象在函数体内不存在。用rest参数代替。
- 不可以使用yield命令,因此箭头函数不能用于Generator函数中
列举了一些不能使用箭头函数的场景:
1. 定义对象方法的时候
const obj = {
str: '111' ,
fn: () => {
console.log(this === window) // => true
}
}
- 解决方式
const obj = {
str: '111' ,
fn () {
console.log(this === obj) // => true
}
}
2. 定义原型方法
function Cat(name) {
this.name = name
}
Cat.prototype.sayCatName = () => {
console.log(this === window) // => true
return this.name
};
const cat = new Cat('Mew')
cat.sayCatName() // => undefined
3. 定义事件回调函数
在全局上下文下定义的箭头函数执行时 this 会指向 window,点击时,浏览器会尝试用 button 作为上下文来执行事件回调函数,但是箭头函数预定义的上下文是不能被修改的,这样 this.innerHTML 就等价于 window.innerHTML,this.innerHTML = 'button'无意义的
const button = document.getElementById('btn');
button.addEventListener('click', () => {
console.log(this === window); // => true
this.innerHTML = 'button'
});
4. 定义构造函数
const Message = (text)=>{
this.text = text;
}
const msg = new Message('message add') //Uncaught TypeError: Message is not a constructor
在创建构造函数的时候,不能使用构造函数。因为,在使用构造函数创建对象实例时,构造函数的上下文是新创建的实例对象。