<分区>
我有以下代码:
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,因为(出于我不知道的原因)如果 getFoo
在addEventListener
函数。
现在,如果我在 myObj.method
中使用箭头函数 -
window.addEventListener('scroll', () => {
this.getFoo();
});
这会起作用,但后来我调用了一个匿名函数,以后不能执行 removeEventListener
。
我怎样才能让它与非匿名函数一起工作?