Z
Z
zlodiak2020-04-25 03:11:49
JavaScript
zlodiak, 2020-04-25 03:11:49

Where does the arrow function get this from?

The same code is written for the regular function and for the arrow function:

const cat = {
  lives: 9,
  jumps: () => {
  	console.log('what?!', this)
  	this.lives--;
  }
};
console.log('cat before', cat.lives);
cat.jumps();
console.log('cat after', cat.lives);

const dog = {
  lives: 9,
  jumps: function() {
  	this.lives--;
  }
};
console.log('dog before', dog.lives);
dog.jumps();
console.log('dog after', dog.lives);


As you can see, the cat does not lose its life after the jump, but the dog does. With the dog, everything is clear - when calling a method, the context is indicated before the dot:
dog.jumps();
Therefore, this inside the function points to the context. Therefore, there is a jumps() method that can access the lives property.

But the situation with the cat is not clear. Please help me figure it out. I understand what is happening like this:
1. the method is also called with the context specified before the dot:
cat.jumps();
2. but since the function is an arrow function, the cat context is ignored (in other words, the arrow function does not associate its this with the cat context)
3. at the same time, for some reason, outputs to console value window 4. I don't understand why exactly window. 5. I correctly assume that once the callconsole.log('what?!', this)
cat.jumps();comes from a global object, then cat is replaced by window?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Robur, 2020-04-25
@zlodiak

in simple terms:
this in the arrow function will be equal to the same as this was equal to in the place where it was defined.

const x= this
setTimeout(() => console.log(this === x))  //true


class X {
  f() {
    const x=this
    setTimeout(() => console.log(x===this)) //true
   }
}

x=this
const obj = {
    y: ()=> console.log(x===this) //true
}

Well, and so on.
If you do not understand what will be in x in such examples - read what this is and how it works, regardless of arrow functions

S
shsv382, 2020-04-25
@shsv382

In the arrow function this will be lexical scoped

I
Ivan Klimenko, 2020-04-25
@yeswell

Here and here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question