箭头功能和这个 [英] Arrow Functions and This

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

问题描述

  var person = {
name:jason,

shout:()=> console.log(我的名字是,this.name)
}

person.shout()//应该打印出我的名字是jason

但是,当我运行这个代码控制台时,只有日志我的名字是。我做错了什么?

解决方案

简短答案:这个 中的 c $ c> 在中提供的代码 b

更长的回答:创建 绑定这个 .getify.com / arrow-this /rel =nofollow noreferrer>没有这个参数或其他特殊名称绑定 - 当对象被创建时,名称这个被发现在封闭的范围内,而不是 person object。您可以通过移动声明来更清楚地看到这一点:

  var person = {
name =Jason
};
person.shout =()=> console.log(我的名字是,这个);

更清楚的是,将其翻译成ES5中箭头语法的模糊近似:

  var person = {
name =Jason
};
var shout = function(){
console.log(我的名字是,this.name);
} .bind(this);
person.shout = shout;

在这两种情况下,这个呼叫功能)指向与的定义相同的范围,而不是将该函数添加到人时附加到的新范围对象。



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

  var person = {
name:Jason,
// ES6method离开:和函数
shout(){
console.log(我的名字是,this.name);
}
};


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

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

解决方案

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

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

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;

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.

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

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

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