微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

什么时候不使用箭头函数

1.定义对象上的方法

const calculate = {
array: [1, 2, 3],
sum: () => {
console.log(this === window); // => true
return this.array.reduce((result, item) => result + item);
}
};

2。Object prototype

同样的规则也适用于在原型对象上定义方法。使用一个箭头函数来定义sayCatName方法,this 指向 window
function MyCat(name) {
this.catName = name;
}
MyCat.prototype.sayCatName = () => {
console.log(this === window); // => true
return this.catName;
};
const cat = new MyCat(‘Mew’);
cat.sayCatName(); // => undefined

3. 动态上下文的回调函数

const button = document.getElementById(‘myButton’);
button.addEventListener(‘click’, () => {
console.log(this === window); // => true
this.innerHTML = ‘Clicked button’;
});

4.调用构造函数

const Message = (text) => {
this.text = text;
};
// Throws “TypeError: Message is not a constructor”
const helloMessage = new Message(‘Hello World!’);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐