箭头函数和 this [英] Arrow Functions and This

查看:30
本文介绍了箭头函数和 this的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试 ES6 并希望在我的函数中包含一个属性

I'm trying out ES6 and want to include a property inside my function like so

var person = {
  name: "jason",

  shout: () => console.log("my name is ", this.name)
}

person.shout() // Should print out my name is jason

然而,当我运行这个代码控制台时,只记录my name is.我做错了什么?

However, when I run this code console only logs my name is. What am I doing wrong?

推荐答案

Short answer: this 指向最近的边界 this - 在提供的代码 this 位于封闭范围内.

Short answer: this points at the nearest bound this - in the code provided this is found in the enclosing scope.

更长的答案:箭头函数在创建时绑定它们的this 没有 thisarguments 或其他绑定的特殊名称 - 在创建对象时名称 this 位于封闭范围内,而不是 person 对象.您可以通过移动声明更清楚地看到这一点:

Longer answer: Arrow functions bind their this when they are created do not have this, arguments or other special names bound at all - when the object is being created the name this is found in the enclosing scope, not the person object. You can see this more clearly by moving the declaration:

var person = {
  name: "Jason"
};
person.shout = () => console.log("Hi, my name is", this);

当翻译成 ES5 中箭头语法的模糊近似时会更加清晰:

And even more clear when translated into a vague approximation of the arrow syntax in ES5:

var person = {
  name: "Jason"
};
var shout = function() {
  console.log("Hi, my name is", this.name);
}.bind(this);
person.shout = shout;

在这两种情况下,this(对于shout 函数)都指向与person 定义相同的作用域,而不是函数附加到的新作用域它被添加到 person 对象中.

In both cases, this (for the shout function) points to the same scope as person is defined in, not the new scope that the function is attached to when it is added to the person object.

不能使箭头函数以这种方式工作,但是,正如@kamituel 在他的回答中指出的那样,您可以利用 ES6 中较短的方法声明模式来获得类似的空间节省:

You cannot make arrow functions work that way, but, as @kamituel points out in his answer, you can take advantage of the shorter method declaration pattern in ES6 to get similar space savings:

var person = {
  name: "Jason",
  // ES6 "method" declaration - leave off the ":" and the "function"
  shout() {
    console.log("Hi, my name is", this.name);
  }
};

这篇关于箭头函数和 this的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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