3

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.

Piotr Białek
  • 2,569
  • 1
  • 17
  • 26

1 Answers1

4

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335