Discover how a simple word like <code>this</code> can save you from confusing and repetitive code!
Why this in objects in Javascript? - Purpose & Use Cases
Imagine you have a list of objects representing different cars, and you want to print each car's brand and model. Without using this, you'd have to manually pass the car details every time you call a function, which can get confusing and repetitive.
Manually passing object details to functions is slow and error-prone. You might forget to pass the right data or mix up parameters. It also makes your code longer and harder to read because you repeat the same information over and over.
The this keyword inside objects lets functions automatically know which object they belong to. This means you can write one function inside the object, and it will always refer to the correct data without extra effort.
function printCar(brand, model) {
console.log(brand + ' ' + model);
}
printCar('Toyota', 'Corolla');const car = {
brand: 'Toyota',
model: 'Corolla',
print() {
console.log(this.brand + ' ' + this.model);
}
};
car.print();Using this in objects makes your code cleaner and lets functions automatically work with the right data inside their own object.
Think of a music player app where each song is an object. Using this, the play button inside each song object can play the correct song without extra instructions.
this helps functions inside objects know which object they belong to.
It reduces mistakes by avoiding manual data passing.
Makes code easier to read and maintain.
Practice
this refer to inside a regular method of an object in JavaScript?Solution
Step 1: Understand
Inside a regular function defined as a method of an object,thisin object methodsthisrefers to the object that owns the method.Step 2: Compare with other contexts
Unlike arrow functions or global functions, regular methods bindthisto the object itself.Final Answer:
The object itself -> Option AQuick Check:
thisin object method = object [OK]
this as the object [OK]- Thinking
thisis always global - Confusing arrow functions with regular functions
- Assuming
thisis the method name
this inside an object?Solution
Step 1: Identify correct method syntax
const obj = { greet() { console.log(this.name); } }; uses the concise method syntax with a regular function, which correctly bindsthisto the object.Step 2: Check other options for errors
const obj = { greet: () => console.log(this.name) }; uses an arrow function, which does not bindthisto the object. Options B and D have invalid syntax for function definitions.Final Answer:
const obj = { greet() { console.log(this.name); } }; -> Option CQuick Check:
Regular method syntax = const obj = { greet() { console.log(this.name); } }; [OK]
- Using arrow functions for methods
- Incorrect function syntax inside objects
- Confusing method shorthand with arrow functions
const person = {
name: 'Alice',
greet() {
console.log(this.name);
}
};
person.greet();Solution
Step 1: Identify
The methodthisinside greet methodgreetis a regular function inside thepersonobject, sothisrefers toperson.Step 2: Access the
Sincenamepropertythisisperson,this.nameis 'Alice'. The console logs 'Alice'.Final Answer:
Alice -> Option AQuick Check:
this.name= 'Alice' [OK]
this points to the object [OK]- Expecting undefined because of arrow function confusion
- Thinking
thisis global - Assuming method returns error
const car = {
brand: 'Toyota',
showBrand: () => {
console.log(this.brand);
}
};
car.showBrand();Solution
Step 1: Identify arrow function issue
Arrow functions do not have their ownthis. Here,this.brandis undefined becausethisis not bound tocar.Step 2: Fix by using regular function
ChangingshowBrandto a regular method bindsthistocar, sothis.brandcorrectly accesses 'Toyota'.Final Answer:
Change arrow function to regular function: showBrand() { console.log(this.brand); } -> Option DQuick Check:
Regular function bindsthiscorrectly [OK]
this [OK]- Using arrow functions for methods
- Trying to bind
thison arrow functions - Ignoring
thiscontext rules
name. Which code correctly uses this to achieve this?const user = {
name: 'Bob',
greet: ???
};
console.log(user.greet());Solution
Step 1: Check method syntax and
greet() { return `Hello, ${this.name}!`; } uses a regular method syntax, sothisbindingthiscorrectly refers to theuserobject.Step 2: Validate other options
greet: () => `Hello, ${this.name}!` uses an arrow function, which does not bindthisto theuserobject. Options B and C have invalid syntax for function definitions.Final Answer:
greet() { return `Hello, ${this.name}!`; } -> Option BQuick Check:
Regular method withthis= greet() { return `Hello, ${this.name}!`; } [OK]
this access in objects [OK]- Using arrow functions for methods
- Incorrect function syntax
- Expecting
thisto work in arrow functions
Ready to prove it?
Pass the test and this pattern moves unknown
