javascript - 函数(带变量)->函数->粗箭头函数->这里显示的第一个函数的变量?

标签 javascript ecmascript-6 arrow-functions

我正在学习词汇 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 。这是一个常规的非胖箭头函数,意味着根据我的理解,词法范围应该停在这里,它不应该上升到更高,但它确实上升了,我不确定为什么。为什么会发生这种情况?

最佳答案

因为您将函数 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 - 因为 b 中的 this 现在引用全局范围。

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();

关于javascript - 函数(带变量)->函数->粗箭头函数->这里显示的第一个函数的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50539156/

相关文章:

javascript - 元素类型无效 : expected a string or a class/function but got: object

javascript - 使用 ES6 箭头函数获取选中的复选框值列表

JavaScript 箭头语法 : What does the equals sign on the right hand side mean?

javascript - 清除 HTML5 Canvas 中的笔划路径(在循环内)

javascript - SumoSelect 的全选选项与选择下拉列表中的其他选项重叠

javascript - 使用 resize 调整 div 大小并使其可拖动

javascript - 为什么我无法使用箭头函数生成 {object}?

Javascript/Jquery 链接更改表单下拉列表

javascript - Switch Case 语句中的错误重复 Const 声明

javascript - 使用回调函数和理解箭头表示法的正确方法