Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
this is a special keyword that refers to the object that's calling the function. Think of it as "whoever is doing the action right now."
this, it refers to THAT object!When you have a method inside an object, this refers to that object
const person = {
name: 'Alice',
age: 25,
introduce: function() {
console.log('Hi, I am ' + this.name);
console.log('I am ' + this.age + ' years old');
}
};
person.introduce();
// Output: Hi, I am Alice
// Output: I am 25 years old
// "this" refers to the person objectthis refers to the object calling the method
const user = {
name: 'Bob',
greet: function() {
console.log('Hello ' + name);
// ❌ ERROR! name is not defined
}
};Without this, JavaScript doesn't know which name you mean
const user = {
name: 'Bob',
greet: function() {
console.log('Hello ' + this.name);
// ✅ Works! this.name = Bob
}
};With this, it knows to look at the user object
Using 'this' to access object properties
this refers to whoever called the function - different objects can use the same method!
const car1 = {
brand: 'Toyota',
showBrand: function() {
console.log('This is a ' + this.brand);
}
};
const car2 = {
brand: 'Honda',
showBrand: function() {
console.log('This is a ' + this.brand);
}
};
car1.showBrand(); // This is a Toyota
car2.showBrand(); // This is a Honda
// Same method, different 'this'!this refers to the calling object
Arrow functions don't have their own this. They inherit it from the surrounding code (called "lexical this").
const person = {
name: 'Alice',
greet: function() {
console.log('Hi, ' + this.name);
}
};
person.greet();
// Output: Hi, Alice
// this = person object ✅const person = {
name: 'Alice',
greet: () => {
console.log('Hi, ' + this.name);
}
};
person.greet();
// Output: Hi, undefined
// this = NOT person! ❌Arrow functions inherit 'this' from surrounding code
const book = {
title: 'JavaScript Basics',
pages: 200,
info: function() {
console.log(title); // ❌ ERROR!
console.log(pages); // ❌ ERROR!
}
};Without this, JavaScript looks for variables named title and pages, not properties
const book = {
title: 'JavaScript Basics',
pages: 200,
info: function() {
console.log(this.title); // ✅ Works!
console.log(this.pages); // ✅ Works!
}
};With this, JavaScript knows to look at the book object's properties
Refers to the object calling the method
Use this.propertyName to get values
Arrow functions don't have their own 'this'
Always use 'this' to access object properties