Skip to content

Instantly share code, notes, and snippets.

@AnimeshPandey
Created February 28, 2021 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AnimeshPandey/2eeb59b3e16ca186cc61bf80d2b3f725 to your computer and use it in GitHub Desktop.
Save AnimeshPandey/2eeb59b3e16ca186cc61bf80d2b3f725 to your computer and use it in GitHub Desktop.
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