Understanding the this Keyword
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 3 of 56.
The this keyword in JavaScript refers to the object that is currently executing the code. It allows you to access properties and methods of the current object.
Let's start with a basic object:
let person = {
name: "John",
age: 30,
greet: function() {
console.log("Hello, my name is " + this.name);
}
};In this example, when we call the greet method:
person.greet();The output will be:
Hello, my name is JohnHere, this.name inside the greet method refers to the name property of the person object.
Challenge
Add a method called getStatus to the player object that returns a string with the player's name and health using the this keyword.
Expected Output Format:"Knight has 70 health"
Cheat sheet
The this keyword refers to the object that is currently executing the code, allowing you to access its properties and methods.
Example of using this in an object method:
let person = {
name: "John",
age: 30,
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
person.greet(); // Output: Hello, my name is JohnInside the method, this.name refers to the name property of the person object.
Try it yourself
const player = {
name: "Knight",
health: 100,
takeDamage: function(damage) {
this.health -= damage;
},
// TODO: Add getStatus method here that returns a string with the player's name and health
};
// Test
player.takeDamage(30);
console.log(player.getStatus()); // Should output: "Knight has 70 health"This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Objects & The this Keyword
Quick Review: ObjectsAdding Methods to ObjectsUnderstanding the this KeywordConstructor FunctionsThe new KeywordRecap Challenge7 Inheritance & The extends Key
InheritanceThe "is-a" RelationshipThe extends KeywordThe super() MethodInheriting Properties&MethodsRecap Challenge2Organizing Code
What are Modules?Exporting with exportImporting with importDefault vs. Named Exports8Organizing OOP Code
Organize Classes into Modules11Project: A Shape Renderer
Setup: Shape Class & ExportCircle Class Inheritance9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge