Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visibility of "this" in Arrow Functions [duplicate]

I have two cases

const test = {
    foo: function (){
        this.bar();
    },
    bar: function (){
        console.log('bar');
    }
}
test.foo();

in this case, everything works correctly.

const test = {
    foo: () => {
        this.bar();
    },
    bar: () => {
        console.log('bar');
    }
}
test.foo();

In second case I get error:

Uncaught TypeError: Cannot read property 'bar' of undefined

I know I can wrote test.bar() in foo function, but I'm interested why this not available in arrow functions scope in this case.

like image 392
Piotr Białek Avatar asked Jan 19 '26 06:01

Piotr Białek


1 Answers

Normally, the value of this in a function depends on how that function is called.

Arrow functions import the value of this from the scope in which the function was created.

In the middle of an object literal, the value of this will depend on what is around the object literal, but certainly won't be the object itself.

like image 84
Quentin Avatar answered Jan 21 '26 19:01

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!