0
0
Javascriptprogramming~5 mins

this in objects in Javascript

Choose your learning style9 modes available
Introduction

The this keyword helps an object refer to itself. It lets the object access its own properties and methods easily.

When you want a method inside an object to use or change the object's own data.
When you want to write reusable code inside objects without repeating the object name.
When you want to keep track of which object is running a function, especially if many objects share the same method.
Syntax
Javascript
const obj = {
  property: 'value',
  method() {
    console.log(this.property);
  }
};

this inside an object method points to the object itself.

Do not use arrow functions for methods if you want this to refer to the object.

Examples
This prints the brand of the car using this.brand.
Javascript
const car = {
  brand: 'Toyota',
  showBrand() {
    console.log(this.brand);
  }
};
car.showBrand();
this.name accesses the name property inside the person object.
Javascript
const person = {
  name: 'Anna',
  greet() {
    console.log('Hello, ' + this.name);
  }
};
person.greet();
Arrow functions do not have their own this, so this prints undefined or the outer this.
Javascript
const obj = {
  value: 10,
  arrowFunc: () => {
    console.log(this.value);
  }
};
obj.arrowFunc();
Sample Program

This program shows how this accesses the title and author properties inside the book object.

Javascript
const book = {
  title: 'JavaScript Basics',
  author: 'Sam',
  describe() {
    console.log(`"${this.title}" is written by ${this.author}.`);
  }
};

book.describe();
OutputSuccess
Important Notes

Inside object methods, this always points to the object calling the method.

If you use this outside an object or in arrow functions, it may not point to the object you expect.

Summary

this lets an object refer to itself inside its methods.

Use regular functions (not arrow functions) for methods to get correct this.

this helps write cleaner and reusable object code.