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

What does quot;thisquot; refer to in arrow functions in ES6?(“这个是什么意思?参考 ES6 中的箭头函数?)

本文介绍了“这个"是什么意思?参考 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.

这篇关于“这个"是什么意思?参考 ES6 中的箭头函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:“这个"是什么意思?参考 ES6 中的箭头函数?

基础教程推荐