1

I'm analyzing the behavior of this in classes and object and have one question which doesn't give me peace. I have this code-snippet:

const obj = {
  a: 5,
  say: () => console.log(this.a)
}

obj.say(); // will log undefined

class A {
  constructor() {
    this.a = 15;
  }

  say = () => console.log(this.a);
}

const a = new A();
a.say(); // will log 15

Why it works with classes examples, but not with singe object?

As I understand it, there is some difference between declaring methods in objects and declaring class methods. But which one?

k4rnage
  • 11
  • 1
  • 1
    Here's a rough explanation for the `class`: [Why are arrow functions as static members values not lexically scoped?](https://stackoverflow.com/q/63937663), for the object, you get `undefined` because arrow functions don't have their own `this` binding, and so it looks in the surrounding scope for the value of `this`, which in your case is `undefined` (as there is no surrounding context where it is defined) – Nick Parsons Aug 05 '23 at 09:44

0 Answers0