• 理解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();

  • 相关阅读:
    实验四 主存空间的分配和回收
    学期总结
    实验三 进程调度模拟程序
    团队项目
    博客参考评论
    dos系统
    学习进度条
    了解和熟悉操作系统
    问题的思考和回答
    Python-关于脚本和冒泡算法
  • 原文地址:https://www.cnblogs.com/FineDay/p/10559926.html
Copyright © 2020-2023  润新知