Sobes.tech
Middle

class Foo { bar = 1; bla = () => console.log(this.bar); baz = function () {console.log(this.bar);}; } new Foo().bla(); new Foo().baz(); Briefly say: `this` is not a scope, but a call context. It is determined not where the function is declared, but how it is called. You can add 3-4 rules: - Regular function call — this is usually undefined in strict mode. - Object method — this points to the object on the left of the dot. - `call / apply / bind` — explicitly set this. - Arrow functions — do not have their own this, they take it from the outer context.

sobes.tech AI

Answer from AI

this is not the scope, but the call context of a function. It is determined not where the function is declared, but how it is called.

Rules:

  • Regular function call — this is usually undefined in strict mode.
  • Object method — this points to the object to the left of the dot.
  • call / apply / bind — allow explicitly setting this.
  • Arrow functions — do not have their own this, they take it from the outer context.

In your example:

class Foo {
  bar = 1;
  bla = () => console.log(this.bar); // arrow function, `this` taken from Foo
  baz = function () {console.log(this.bar);}; // regular function, `this` depends on the call
}

new Foo().bla(); // `this` — instance of Foo, outputs 1
new Foo().baz(); // `this` — also instance of Foo, outputs 1

Here, baz is called as a method of the object, so this is the class instance. If baz is called separately, for example, const f = new Foo(); const fn = f.baz; fn(); — then this would be undefined.

class Foo { bar = 1; bla = () => console.log(this.bar)… - sobes.tech