javascript - 箭头函数和这个

标签 javascript this ecmascript-6 arrow-functions

这个问题在这里已经有了答案:





Methods in ES6 objects: using arrow functions

(6 个回答)


4年前关闭。




我正在尝试 ES6 并希望在我的函数中包含一个属性,就像这样

var person = {
  name: "jason",

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

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

但是,当我运行此代码控制台时,只记录 my name is .我究竟做错了什么?

最佳答案

简短回答:this点在最近的边界this - 在提供的代码中 this在封闭范围内找到。
更长的答案:箭头函数
do not have this , arguments or other special names bound at all - 创建对象时的名称this在封闭范围内找到,而不是 person目的。通过移动声明,您可以更清楚地看到这一点:

var person = {
  name: "Jason"
};
person.shout = () => console.log("Hi, my name is", this);
当翻译成 ES5 中箭头语法的模糊近似时,更加清晰:
var person = {
  name: "Jason"
};
var shout = function() {
  console.log("Hi, my name is", this.name);
}.bind(this);
person.shout = shout;
在这两种情况下,this (对于喊功能)指向与 person 相同的范围定义在,而不是函数添加到 person 时所附加的新范围目的。
你不能让箭头函数那样工作,但是,正如@kamituel 在 his answer 中指出的那样,您可以利用 ES6 中较短的方法声明模式来节省类似的空间:
var person = {
  name: "Jason",
  // ES6 "method" declaration - leave off the ":" and the "function"
  shout() {
    console.log("Hi, my name is", this.name);
  }
};

关于javascript - 箭头函数和这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28798330/

相关文章:

javascript - 使用 JavaScript ES6 箭头函数的立即函数

javascript - 如何使用 faker.js 生成大写字母

javascript - 如何将 id 放在 url 中间

javascript - 在 JavaScript 中解构对象时如何绑定(bind)方法?

javascript - 使用 JS .call() 方法的原因?

javascript - 为什么这里需要 'this' 关键字?它指的是什么?

javascript - 在同一函数中创建 <p> 元素并更改样式

javascript - 防止页面滚动 ui-grid 字段单击

javascript - RxJS 先 take 然后 throttle 等待

javascript - 当 Promise 状态被拒绝或解决时