0
0
Javascriptprogramming~5 mins

What this keyword represents in Javascript

Choose your learning style9 modes available
Introduction

The this keyword helps you access the current object or context inside a function or method.

When you want to refer to the object that owns the current code.
When you write methods inside objects and want to access other properties of the same object.
When you handle events and want to know which element triggered the event.
When you use constructor functions or classes to create objects and want to set properties.
When you want to write reusable code that works with different objects.
Syntax
Javascript
function example() {
  console.log(this);
}

this value depends on how the function is called, not where it is defined.

In global code, this usually refers to the global object (like window in browsers).

Examples
this refers to obj, so it prints 'Alice'.
Javascript
const obj = {
  name: 'Alice',
  greet() {
    console.log(this.name);
  }
};
obj.greet();
In non-strict mode, this is the global object. In strict mode, it is undefined.
Javascript
function show() {
  console.log(this);
}
show();
this inside the class refers to the instance p.
Javascript
class Person {
  constructor(name) {
    this.name = name;
  }
  sayName() {
    console.log(this.name);
  }
}
const p = new Person('Bob');
p.sayName();
Sample Program

This program shows how this refers to the car object inside the method.

Javascript
const car = {
  brand: 'Toyota',
  showBrand() {
    console.log(`This car is a ${this.brand}`);
  }
};
car.showBrand();
OutputSuccess
Important Notes

Arrow functions do not have their own this; they use this from the surrounding code.

Be careful when extracting methods from objects; this may lose its original meaning.

Summary

this points to the current object or context.

Its value depends on how a function is called.

It helps write flexible and reusable code.