0

Since this in arrow functions refers to lexical context, it is expected that the following code would log the object itself:

const arrow = () => {
  console.log(this);
};
const object = {
  render() {
    setTimeout(arrow, 1000);
  },
};
object.render();

However it actually logs the global object. This is confusing to me because when I use an inline arrow function, it works fine and logs the obj:

const object = {
  render() {
    setTimeout(() => {
      console.log(this);
    }, 1000);
  },
};
object.render();

With an inline version of the same arrow function the code logs the object itself, which is exactly what I want. I'm really confused about why this happens. They are both arrow functions, aren't they?

*Update: Thanks for the answers! So this in arrow functions keeps the reference when they were defined. But what about this in a class? e.g.,

class MyClass {
    handleChange = () => {
      console.log(this);
    };
    render() {
      setTimeout(this.handleChange, 1000);
    }
  }
  const myclass = new MyClass();
  myclass.render();

In this case, this in handleChange refers to the object myclass. But if it keeps the original reference, shouldn't it refers to the global when it was defined?

BinaryDog
  • 13
  • 2
  • with arrow functions, think of it like this: `this` is unchanging. Whatever `this` means where you define the function, `this` will always mean the same thing inside the function whenever you call it. – TKoL Dec 30 '20 at 09:06
  • Exactly, lexical context. `this` will be whatever `this` was where `const arrow = () => ...` was *defined*. – deceze Dec 30 '20 at 09:07
  • `class .. { foo = () => ... }` creates bound instance methods: https://stackoverflow.com/a/45898085/476 – deceze Dec 30 '20 at 09:42
  • Thanks. It makes so much sense to me now. – BinaryDog Dec 30 '20 at 09:56

0 Answers0