Created
February 28, 2021 00:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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