“这个"是什么意思?参考 ES6 中的箭头函数?

我在几个地方读到过,主要区别在于 this 在词法上绑定在箭头函数中.这一切都很好,但我实际上并不知道这意味着什么.

I've read in several places that the key difference is that this is lexically bound in arrow functions. That's all well and good, but I don't actually know what that means.

我知道这意味着它在定义函数主体的大括号范围内是唯一的,但我实际上无法告诉您以下代码的输出,因为我不知道 this 是什么指,除非它指的是胖箭头函数本身....这似乎没有用.

I know it means it's unique within the confines of the braces defining the function's body, but I couldn't actually tell you the output of the following code, because I have no idea what this is referring to, unless it's referring to the fat arrow function itself....which doesn't seem useful.

var testFunction = () => { console.log(this) };
testFunction();

推荐答案

箭头函数捕获封闭上下文的this

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
}

var p = new Person();

因此,为了直接回答您的问题,箭头函数内的 this 将具有与分配箭头函数之前相同的值.

So, to directly answer your question, this inside your arrow function would have the same value as it did right before the arrow function was assigned.

相关文章