Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript 'this' returns undefined inside object [duplicate]

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?

like image 338
galingong Avatar asked Apr 20 '18 10:04

galingong


People also ask

Why is this undefined JavaScript object?

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.

Why function returns undefined?

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.


1 Answers

From 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.

like image 100
Mamun Avatar answered Sep 21 '22 21:09

Mamun