Javascript 'this' 返回未定义的内部对象

标签 javascript object ecmascript-6 this arrow-functions

<分区>

我有以下代码:

let myObj = {
  foo: "bar",
  getFoo: function() {
    console.log(this.foo);
  },
  method: function() {
    if (true) {
      window.addEventListener('scroll', this.getFoo);
    } else {
      window.removeEventListener('scroll', this.getFoo);
    }
  }
}

window.addEventListener('click', () => {
  myObj.method();
});

它返回 undefinded,因为(出于我不知道的原因)如果 getFooaddEventListener 函数。 现在,如果我在 myObj.method 中使用箭头函数 -

window.addEventListener('scroll', () => {
  this.getFoo();
});

这会起作用,但后来我调用了一个匿名函数,以后不能执行 removeEventListener。 我怎样才能让它与非匿名函数一起工作?

最佳答案

来自 MDN :

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

关于Javascript 'this' 返回未定义的内部对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49939968/

相关文章:

javascript - 请解释一下这个 ECMASCRIPT 代码和语法

Javascript 数组元素消失

javascript - 有没有办法计算一个文件夹中有多少个文件,然后将其导入到变量中?

php - 从 Eloquent 查询更改对象数组中的键

java - 为什么这个教科书程序无法识别我的 Point2D 对象?

Javascript 访问静态子属性

javascript - 如何更新iframe的高度?

Javascript:检查 Twitter 推文是否存在

javascript - 数组 + 矩阵 = 对象数组

javascript - 如何在没有 this 关键字的类中创建方法来返回组件?