箭头函数是ES6中新增的使用胖箭头(=>)定义函数的方法
箭头函数省略了关键字function
<script type="text/javascript"> let fun1 = function(a,b){ return a + b }; //箭头函数的声明 let fun2 = (a,b) => { return a + b }; //箭头函数的调用 let result = fun2(1,2)//3 </script>
箭头函数中的this始终指向的是函数声明时所在作用域下的this,也就是说this是静态的
使用场景:箭头函数适合与this无关的回调,定时器以及数组的方法回调
示例代码一
window.name = "window" let obj = { name:"Penrose", getName:() =>{ //此时的this指向的是window作用域下的this console.log(this.name); } }; obj.getName()//输出的是window
<html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> .demo{ width: 300px; height: 300px; background-color: pink; } </style> </head> <body> <div class="demo"></div> <script type="text/javascript"> //需求:点击div后,2s后背景变为purple let div = document.querySelector(".demo"); div.addEventListener("click",function(){ setTimeout(()=>{ //这个箭头函数中的this指向的是此箭头函数声明时所在的作用域下的this //即this指向在监听器下的作用域的this,而监听器中的this指向的就是事件源 this.style.backgroundColor = "purple"; },2000) }) </script> </body> </html>
<script type="text/javascript"> let Person = (name,age) =>{ this.name = name; this.age = age; }; let p = new Person("Penrose",22) //错误信息 //Uncaught TypeError: Person is not a constructor </script>
<script type="text/javascript"> let fn = () =>{ console.log(arguments) } fn(1,2,3) //错误信息 //arguments is not defined </script>