理解es6 中 arrow function的this

箭头函数相当于定义时候,普通函数.bind(this)
箭头函数根本没有自己的this,导致内部的this就是定义时候的外层代码块中的this。
外层代码块中的this,则取决于执行时候环境上下文context中的this
并不是所有的{}都可以代表是上下文环境或者代码块,例如  {x:1,y:2} ,就是简简单单的对象。
但是function () {
  这里是代码块,有上下文context环境,例如参数,属性,变量等
}

还有就是context为window(global)的情况。

通过实例来分析箭头函数的this。

var name = 'nnmm'

var obj = {
  name: 'name1',
  func: () => {    //不推荐这样的方式(使用对象字面量的时候,最好不要在其定义的方法里使用箭头函数)
    console.log(this.name)
  },
  func1: function (){
    console.log(this.name)
  },
  son: {
    name: 'name-son',
    func: function(){
      console.log(this.name)
    },
    func1: ()=>{
      console.log(this.name)
    }
  }
}
obj.func()
obj.func1()
obj.son.func()
obj.son.func1()

obj.func为箭头函数,定义它的this为外层上下文的this,即为window(global)。

var obj1={
  num:4,
  fn:function(){
    var f=() => {
      console.log("hello----->",this);  //此处的this取决与外层代码fn函数的执行环境
      setTimeout(() => {
        console.log("world----->",this); //此处的this取决与外层代码fn函数的执行环境
      });
    }
    f();
  }
}
obj1.fn();
var f = obj1.fn;
f();

原文地址:https://www.cnblogs.com/FineDay/p/10559926.html