我们知道箭头函数有一个作用是解决 this 的指向问题. 函数的 this 是谁调用, 就指向谁; 箭头函数的 this 是在哪定义就指向谁, 那么如果是在全局定义执行箭头函数, this 指向谁呢?
测试
- <!DOCTYPE html>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>
- Document
- </title>
- </head>
- <body>
- <script>
- // 箭头函数
- (() = >{
- console.log(this);
- })();
- // output: Windows 对象
- // 函数
- (function() {
- console.log(this);
- })();
- // output: Windows 对象
- </script>
- </body>
- </HTML>
结果
在全局定义执行箭头函数, this 也是指向 Windows.
来源: http://www.jianshu.com/p/ae0cc70f8e61