ES6 的箭头函数对 this 处理有什么好处?
ES6 中引入了胖箭头函数 () => {}
,除了比原来的函数 function(){}
写法更简单,另一个很大的好处就是,它不会改变 this 的指向,这个实际中是非常方便的。
文字叙述不直观,视频中来演示一下就比较清楚了,请观看视频。
最终代码写成这样:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> .btn { background-color: teal; display: inline-block; color: white; padding: 10px 20px; cursor: pointer; } .on { background-color: deeppink; } </style></head><body> <div class="btn"> Click Me </div> <script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.js"></script> <script> $('.btn').on('click',function() { console.log(this); setTimeout(() => { console.log(this); $(this).toggleClass('on'); }, 1000) }); </script></body></html>