Answer the question
In order to leave comments, you need to log in
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);
dog.jumps();
cat.jumps();
console.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
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
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question