箭头函数
一.箭头函数的指向
1.1先出一道题
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    var arr=[1,2,3];
    this.arr.forEach((item)=>{
      console.log(this);
    })
  </script>
</body>
</html>
上面的打印的this指向谁?this.arr的arr对象?
1.2箭头函数的具体指向
箭头函数的具体指向绑定定义时所在的作用域,而不是指向运行时所在的作用域。
例子1
  setTimeout(()=>{
        console.log("id",this.id);//id:21
    },100)
   var id = 21;
//此箭头函数绑定了定义时所在的作用域,全局作用域下
例子2
function foo() {
  setTimeout(() => {
    console.log('id:', this.id);//id:42
  }, 100);
}
var id = 21;
foo.call({ id: 42 });
////此箭头函数绑定了定义时所在的作用域,foo的函数作用域下,所以this才指向了{id:42}
二.使用箭头函数的注意点
2.1注意1
箭头函数转成 ES5 的代码如下。
// ES6
function foo() {
  setTimeout(() => {
    console.log('id:', this.id);
  }, 100);
}
// ES5
function foo() {
  var _this = this;
  setTimeout(function () {
    console.log('id:', _this.id);
  }, 100);
}
上面代码中,转换后的 ES5 版本清楚地说明了,箭头函数里面根本没有自己的this,而是引用外层的this。
结论:箭头函数没有自己的this,所以才绑定了定义时所在的作用域
2.2注意2
除了this,以下三个变量在箭头函数之中也是不存在的,指向外层函数的对应变量:arguments、super、new.target。
function foo() {
  setTimeout(() => {
    console.log('args:', arguments);
  }, 100);
}
foo(2, 4, 6, 8)
// args: Argumnets(4)[2, 4, 6, 8]
2.3注意3
箭头函数没有自己的this,所以当然也就不能用call()、apply()、bind()这些方法去改变this的指向。
(function() {
  return [
    (() => this.x).bind({ x: 'inner' })()
  ];
}).call({ x: 'outer' });
// ['outer']
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号