'This'
The Ninja and Their Dojo
Imagine a ninja in their dojo. The ninja (this
) can perform various tasks (methods) within the confines of the dojo (object). Depending on which part of the dojo the ninja is in, their actions (methods) may have different outcomes or utilize different tools available in that specific area (context). Just as the ninja's actions are influenced by their location in the dojo, the behavior of this
in JavaScript is determined by the context in which a function is called.
Understanding this
in JavaScript is akin to a ninja mastering their environment within the dojo. With practice, you'll learn to navigate and utilize this
effectively in your coding journey.
Contextual Echoes
In the dojo's heart,
Context shapes the ninja's path,
this
reveals its art.
The Samurai Clan
/* This example shows how this refers to different contexts: inside the Dojo class, it refers to the instance of the dojo, whereas with outsideDojoActivity.call(myDojo), we explicitly set this to refer to myDojo.
*/
class Dojo {
constructor(name) {
this.name = name;
this.ninja = "Hiro";
}
// Method to display who is in the dojo
whoIsHere() {
console.log(`${this.ninja} is in the ${this.name} dojo`);
}
}
const myDojo = new Dojo("Zen Garden");
myDojo.whoIsHere(); // "Hiro is in the Zen Garden dojo"
// Using a function outside the class context
function outsideDojoActivity() {
console.log(`${this.ninja} is outside the dojo`);
}
outsideDojoActivity.call(myDojo); // "Hiro is outside the dojo"
Object Orientated Programming in Javascript
Territory Determines Action: TDA
Just like a ninja's actions are determined by the territory they are in, the value of this
is determined by the context in which the function is executed.
Concept Checking Questions
-
What does
this
refer to in a global context?- In a global context,
this
refers to the global object (window
in a web browser,global
in Node.js).
- In a global context,
-
How does
this
behave inside an arrow function?- Inside an arrow function,
this
retains the value of the context where the arrow function was defined, not where it is called.
- Inside an arrow function,
-
What is the outcome of using
this
in a method called by a different object?- The value of
this
refers to the object calling the method, not necessarily the object that defined the method.
- The value of