【发布时间】:2019-08-06 02:38:11
【问题描述】:
我正在学习 ES6,我只是想将我的 ES5 知识转换为 ES6。
这是我的 ES5 代码:
function click() {
this.className += ' grab';
setTimeout(() => (this.className = 'remove'), 0);
};
这是我的 ES6 代码:
const click = () => {
this.className += ' grab';
setTimeout(() => (this.className = 'remove'), 0);
console.log('RENDERING');
}
我的问题是 this.className += 'grab'; 和 setTimeout(() => (this.className = 'remove'), 0); 没有'不运行该功能。但是 console.log 会显示在日志中。
此方法是否不适用于箭头函数?
【问题讨论】:
-
this不是一种方法,并且在箭头函数内部是不同的 - 阅读 documentation 以了解区别...didn't run the function是的,确实如此,只是你不知道是什么你还在做 -
this关键字在箭头函数中的作用不同。 Read this section 的文档。 -
Aside - 考虑使用
el.classList.add('grab')(和el.classList.remove('grab'))而不是手动操作类名字符串。 more info -
这表明并不是所有的函数都应该仅仅因为箭头函数很酷就被转换为箭头函数:p 箭头函数有特定的用途,只能在适当的时候使用
标签: javascript function arrow-functions