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.
An arrow function just borrows
thisandargumentsfrom the outer scope (it doesn't have own). The outer scope isprintCard()which is called withthis = messageConfig, and argumentsarg1andarg2. You can access the array withthis.signatoriesor use the third argument offorEach()which is the array of being iterated.Arrow functions are useful as callbacks inside methods since you have
thisinside them as an instance a method is called on, so no need in bind/call/apply/self as with a usualfunction.