Middle
class Foo { bar = 1; bla = () => console.log(this.bar); baz = function () {console.log(this.bar);}; } new Foo().bla(); new Foo().baz(); Briefly put: `this` is not a scope, but the call context of a function. It is determined not where the function is declared, but how it is called. You can add 3-4 rules: - Normal 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.
sobes.tech AI
Vastus AI-lt
this — это не область видимости, а контекст вызова функции. Он определяется не там, где функция объявлена, а там, как она вызвана.
Правила:
- Обычный вызов функции —
thisобычноundefinedв strict mode. - Метод объекта —
thisуказывает на объект слева от точки. call/apply/bind— позволяют явно задатьthis.- Стрелочные функции — своего
thisне имеют, берут его из внешнего контекста.
В твоём примере:
class Foo {
bar = 1;
bla = () => console.log(this.bar); // стрелочная, this из Foo
baz = function () {console.log(this.bar);}; // обычная, this зависит от вызова
}
new Foo().bla(); // this — объект Foo, выведет 1
new Foo().baz(); // this — объект Foo, выведет 1
Если вызвать baz отдельно, например, const f = new Foo(); const fn = f.baz; fn(); — this будет undefined или глобальным объектом.