Arrow functions have a lexical this
which means that the value of this
inside the function is the same as the value of this
outside the function.
It does not mean that this
points to an object containing all the variables from outside the function.
const anObject = {
aValue: "example value",
aMethod: function() {
console.log("aMethod", this.aValue);
const arrow = () => {
console.log("arrow", this.aValue);
}
arrow();
}
}
anObject.aMethod();
const copyOfAMethod = anObject.aMethod;
copyOfAMethod();
Because aMethod
is called as a method on anObject
, the value of this
inside aMethod
is anObject
.
Because arrow
is declared inside aMethod
, the value of this
is the same as it is for aMethod
.
If the function is copied elsewhere so it has a different this
value, then the arrow function created when the copy is called it will have the same different value.