Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Helpful example code to demonstrate the use of "this" in JavaScript for my article at https://anmshpndy.medium.com/how-well-do-you-know-this-ce4355bc9b
// Example 10. Implicit versus Explicit
function catchPokémon() {
console.log("Pokémon caught : ", this.name);
}
var firstAttempt = {
name : "Flareon",
catchPokémon : catchPokémon
}
var secondAttempt = {
name : "Vaporeon",
catchPokémon : catchPokémon
}
//// Implicit binding
firstAttempt.catchPokémon();
// "Pokémon Caught : Flareon"
secondAttempt.catchPokémon();
// "Pokémon Caught : Vaporeon"
//// Explicit binding to swap contexts
firstAttempt.catchPokémon.call(secondAttempt);
// "Pokémon Caught : Vaporeon"
secondAttempt.catchPokémon.call(firstAttempt);
// "Pokémon Caught : Flareon"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment