1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta http-equiv="X-UA-Compatible" content="IE=edge">
6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
7 <title>Document</title>
8 </head>
9 <body>
10 <script>
11 /**
12 * 箭头函数中的this是在定义函数的时候绑定的,而不是在执行函数的时候绑定的
13 * 箭头函数中,this指向的固定化,而不是因为箭头函数内部有绑定函数的机制,实际原因是箭头函数根本没有自己的this,
14 * 导致内部的this就是外层代码的this。正因为没有this,所以也不能用作构造函数。
15 * 箭头函数中的this是在定义函数的时候绑定的
16 *
17 **/
18
19 var x = 11;
20 var obj = {
21 x: 22,
22 say: () =>{
23 console.log(this.x);
24 }
25 }
26 obj.say() //因为是箭头函数 ,它没有自己的this 只能调用外层代码块的this 所以结果是:11
27
28
29 var obj2 = {
30 birth:1990,
31 getAge: function () {
32 var b = this.birth; // b = 1990
33 var fn = () => new Date().getFullYear() - this.birth;//因为箭头函数的this是在getAge函数总的,this所以指向的是父级的obj2中的this
34 return fn();
35 }
36 };
37 obj2.getAge();//结果:当前年份-1990
38 </script>
39 </body>
40 </html>