So as I am reading on the execution context in javascript and how does it works, everything seemed fine until I tried some examples on the this value of callback arrow functions.
const printCard = function () {
this.signatories.forEach((signatory) =>
console.log(this) /* expected to return signatories, returned messageConfig */
);
};
const messageConfig = {
closing: {
Thor: "Admiration, respect, and love",
Loki: "Your son",
},
signatories: ["Thor", "Loki"],
};
printCard.call(messageConfig);
Here since forEach is prototypal method of signatories, I expected the callback (the arrow function) to automatically take the this value from the enclosing context (forEach in this case). However, it seemed to return the messageConfig which reminds me of lexical scoping a little bit.
2
Answers
An arrow function just borrows
this
andarguments
from the outer scope (it doesn’t have own). The outer scope isprintCard()
which is called withthis = messageConfig
, and argumentsarg1
andarg2
. You can access the array withthis.signatories
or use the third argument offorEach()
which is the array of being iterated.Arrow functions are useful as callbacks inside methods since you have
this
inside them as an instance a method is called on, so no need in bind/call/apply/self as with a usualfunction
.Array.prototype.forEach()
doesn’t pass athis
context to its callback function. It passes the array it’s looping over as the third argument. So if you want to get signatories, useAlso, arrow functions don’t accept a passed
this
context. They inherit the context from the defining scope. Since you’re binding the context tomessageConfig
when you useprintCard.call()
, that’s the value ofthis
inprintCard()
and also the callback function.If you were to change the callback function to a regular function,
this
would be thewindow
object in a browser, or theglobal
object in node.js, unless the code is in strict mode.