0

Context of this doesn't work as expected. I have described my issue in as comments in the code below.

const dog = {

    //arrow function
    bark: () => {
        console.log(this);
    },

    makeBark(){
        // this here refers to the dog object
        // (as it is a normal function) 
        // so inside the bark function , shouldn't
        // this refer to the dog object ?  
        this.bark();
    },    

};        

dog.makeBark(); // this is the problematic function

I dont understand WHY dog.makeBark() prints window object . The parent scope of bark function is the dog object

Tilak Madichetti
  • 4,110
  • 5
  • 34
  • 52
  • 1
    Can you please add a description of what is your problem with the function and what do you expect? – Shahzad Jun 28 '19 at 16:55
  • 1
    The arrow function is never going to use anything other than the lexical `this`. It doesn't matter how you call it. – Mark Jun 28 '19 at 16:56
  • 1
    Remember that arrow functions are *lexically bound*. The lexical scope during an object initialisation is *not* the object. – VLAZ Jun 28 '19 at 16:56
  • 1
    @Quentin I don't think its a duplicate because the OP already knows the reason that why it is printing `window` object. He is confused in the third part – Maheer Ali Jun 28 '19 at 17:00

1 Answers1

1

The this of arrow function will be the this of its parent scope where its declared not where its called.

In the above example you are just calling bark from another function. This code doesn't change this of bark. Also this for an arrow function will remain same throughout the code and can never be changed implicitly or explicitly.

Maheer Ali
  • 35,834
  • 5
  • 42
  • 73