ES6箭头函数

1.箭头函数的基本使用

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>Title</title>
 6 </head>
 7 <body>
 8 
 9 <script>
10   // 箭头函数的写法
11   const 函数名 = (参数列表) => {
12 
13   }
14 
15   const ccc = () =>{
16 
17   }
18 </script>
19 </body>
20 </html> 

2.箭头函数参数和返回值

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>Title</title>
 6 </head>
 7 <body>
 8 
 9 <script>
10   //参数问题
11   //1.1 只放入1个参数 ()可以省略
12   const power1 = (num) =>{
13     return num * num
14   };
15   const power2 = num =>{
16     return num * num
17   }
18 
19   //1.2 放入两个参数
20   const sum = (num1,num2) =>{
21     return num1 + num2
22   }
23 
24   // 代码行数问题
25 
26   // 1.1箭头函数里面多行代码正常写
27   const hello = () =>{
28     console.log("hello word");
29     console.log("hello Vue");
30   }
31 
32   // 1.2 箭头函数里面只有一行代码可以简写
33   const mul = (num1 , num2) =>{
34     return mun1 * num2
35   }
36   // 简写,自动return返回
37   const mul2 = (num1 ,num2) => num1 * num2 ;
38   const demo = () => "没有返回值的时候,先执行后返回一个undefined"
39 
40   //调用验证下
41   console.log(mul2(20,30));
42 </script>
43 </body>
44 </html>

3.箭头函数中this的使用 

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>Title</title>
 6 </head>
 7 <body>
 8 
 9 <script>
10 // 将一个函数作为一个参数传到另一个函数的时候用箭头函数最多(高阶函数的时候)
11 
12   //问题: 箭头函数中的this是如何查找的
13   //答案: 向外层作用域中,一层层往外查找this,直到有this的定义(也就是最近作用域中的this)
14   //补充:普通function(){}的this就是window
15   const obj1 = {
16     aaa(){
17       setTimeout(function () {
18         console.log(this)   // window
19       });
20 
21       setTimeout(()=>{
22         console.log(this)   // obj1
23       })
24     }
25   };
26   obj1.aaa();
27 
28   const obj2 = {
29     bbb(){
30       setTimeout(function () {
31         setTimeout(function () {
32           console.log(this)         // window
33         });
34 
35         setTimeout(()=>{
36           console.log(this)         // window
37         });
38       });
39 
40       setTimeout(()=>{
41         setTimeout(function () {
42           console.log(this)            //window
43         });
44         setTimeout(()=>{
45           console.log(this)            // obj2
46         })
47       })
48     }
49   };
50 obj2.bbb()
51 </script>
52 </body>
53 </html>
原文地址:https://www.cnblogs.com/zwnsyw/p/12305506.html