什么是“这个”请参考ES6中的箭头功能? [英] What does "this" refer to in arrow functions in ES6?

查看:137
本文介绍了什么是“这个”请参考ES6中的箭头功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在几个地方阅读过,主要区别是这个在箭头函数中是词法绑定的。这很好,但我实际上并不知道这是什么意思。



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

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


解决方案

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

  function Person(){
this.age = 0;

setInterval(()=> {
this.age ++; // | this |正确地指人物对象
},1000);
}

var p = new Person();

所以,直接回答你的问题,这个在你的箭头函数内部将具有与分配箭头函数之前相同的值。


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.

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

解决方案

Arrow functions capture the this value of the enclosing context

function Person(){
  this.age = 0;

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

var p = new Person();

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中的箭头功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆