代码之家  ›  专栏  ›  技术社区  ›  user2924127

函数(带变量)->函数->胖箭头函数->此处显示的第一个函数的变量?

  •  2
  • user2924127  · 技术社区  · 7 年前

    我正在学习词汇 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();

    所以我希望控制台。日志语句要打印出来 this.a .它不存在于fat arrow函数上下文中,因此它会上升一级到匿名函数级。也没有 这A. 在这里这是一个常规的非胖箭头函数,这意味着我理解的词法范围应该到此为止,它不应该再上升了,但它确实上升了,我不知道为什么。为什么会这样?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Nisarg Shah    7 年前

    因为你在调用函数b作为 d.b 是的 this 这是目标吗 d 所以 this.a 相当于 d.a .正如您已经观察到的,箭头功能将 从其父范围,因此它能够解决 这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 -因为 在…内 b 现在指的是全球范围。

    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
  •  1
  •   Damon    7 年前

    阅读 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() 会凝固 d 在…内 b 。在arrow函数中,此上下文将被保留。