cod*_*ney 6 javascript function arrow-functions
我正在学习ES6,我只想将我的ES5知识转换为ES6。
这是我的ES5代码:
function click() {
this.className += ' grab';
setTimeout(() => (this.className = 'remove'), 0);
};
Run Code Online (Sandbox Code Playgroud)
这是我的ES6代码:
const click = () => {
this.className += ' grab';
setTimeout(() => (this.className = 'remove'), 0);
console.log('RENDERING');
}
Run Code Online (Sandbox Code Playgroud)
我的问题是this.className + ='抓住'; 和setTimeout(()=>(this.className ='remove'),0); 没有运行该功能。但是console.log会显示在日志中。
是该方法不上箭头职能的工作?
确实没有足够的上下文可以给您一个很好的答案,但是有一件事很突出。箭头功能保持范围,因此this内部function click()和const click很可能是不同的。在ES6版本中,this将引用this闭包创建过程中的所有内容,而这可能不是您想要的。
MDN的箭头功能将其清除:
箭头功能没有自己的功能
this.
…这意味着this将从声明范围继承。
ES6箭头函数不仅是一种声明函数的新方法,function myFunction(...)语法本身并没有错,也不会消失。箭头函数在将函数作为参数传递时避免了冗长(例如forEach),并且this在某些情况下避免了将函数重新绑定到其他函数的麻烦。将所有函数声明转换为箭头语法不是升级。