I have following code:
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();
});
It returns undefinded, since (for reasons unknown to me) this refers to the window object if getFoo is called as a callback in an addEventListener function.
Now if I used an arrow function inside myObj.method - 
window.addEventListener('scroll', () => {
  this.getFoo();
});
This would work, but then I called an anonymous function and can't do removeEventListener later.
How could I get this working with a non-anonymous function?
undefined is a property of the global object. That is, it is a variable in the global scope. A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value.
A function returns undefined if a value was not returned . Note: While you can use undefined as an identifier (variable name) in any scope other than the global scope (because undefined is not a reserved word), doing so is a very bad idea that will make your code difficult to maintain and debug.
From MDN:
An arrow function expression has a shorter syntax than a function expression and does not have its own
this,arguments,super, ornew.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With