理解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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值