【问题标题】:function (with variable) -> function -> fat arrow function- >variable from first function showing here?函数(带变量)-> 函数-> 胖箭头函数-> 此处显示的第一个函数的变量?
【发布时间】:2018-05-26 03:48:02
【问题描述】:

我正在学习词汇 this 被传递,我的理解是一个胖箭头从它自己或它上面的函数中获取它的“this”。如果这是一个常规函数,我的理解是它不会从高于此的函数中获得this。例如,这是我认为不应该运行的代码:

function test() {
  this.a = 5; // test()' variable
  this.b = function() {
    //this is a fat arrow function so console log below could grab the this from this function's space, but not higher than this, but it does?
    this.c = setTimeout(() => {
      console.log(this.a);
    }, 1000);
  }
}
var d = new test();
d.b();

所以我希望 console.log 语句想要打印出 this.a 。它在胖箭头函数上下文中不存在,因此它上升到匿名函数级别。这里也没有this.a。这是一个常规的非胖箭头函数,这意味着我理解的词汇范围应该停在这里,它不应该再上升,但确实如此,我不知道为什么。为什么会这样?

【问题讨论】:

  • var d = new test(); 是我相信的根执行上下文。词法作用域查找最终找到变量a
  • b 函数是测试的一部分/附加到测试,它们具有相同的 this 指针。

标签: javascript ecmascript-6 arrow-functions


【解决方案1】:

因为您将函数 b 调用为 d.b,所以它的 this 是对象 d。所以this.a 等价于d.a。正如您已经观察到的,箭头函数将从其父作用域携带this,因此它能够将this.a 解析为d.a

function test() {

  this.a = 5; // test()' variable
  this.b = function() {
    console.log("this.a in b: ", this.a);
  
    this.c = setTimeout(() => {
      console.log("this.a in c: ", this.a);
    }, 1000);
  }
}

var d = new test();
d.b();

如果您将d.b 拉到一个单独的变量中,然后调用它会发生什么?你会得到undefined - 因为thisb 中现在指的是全局范围。

function test() {

  this.a = 5; // test()' variable
  this.b = function() {
    console.log("this.a in b: ", this.a);
    console.log("this === window: ",this === window);
  
    this.c = setTimeout(() => {
      console.log("this.a in c:", this.a);
    }, 1000);
  }
}

var d = new test();
var myNewFunction = d.b;

myNewFunction();

【讨论】:

    【解决方案2】:

    阅读this(双关语)

    “当函数作为对象的方法被调用时,其this被设置为调用该方法的对象”

    考虑这个简化的例子:

    "use strict";
    
    var obj = {
      name: "obj",
      a: function() {
        return this
      }
    }
    var a = obj.a
    var obj2 = {
      name: "obj2"
    }
    obj2.a = a
    
    console.log(
      obj.a(), // => obj
      a(), // => window | undefined (based on strict mode)
      obj2.a() // => obj2
    )

    同样,在您的示例中,调用d.b() 会将this 设置为db。在您的箭头函数中,此上下文将被保留。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-15
      相关资源
      最近更新 更多