JavaScript "this" Keyword

Definition

The this keyword in JavaScript refers to the object that is executing the current function. Its value is determined by how a function is called.

Key Points

Why this is Needed

It allows functions and methods to operate on the object they belong to, making code reusable and dynamic.

Syntax


// Inside a method
object.method() {
    console.log(this);
}

// Inside a constructor
function Person(name) {
    this.name = name;
}

// Arrow function (lexical this)
let arrowFunc = () => console.log(this);
            

Examples

1. Global Context

console.log(this); // Window object in browser

2. Function Context

function showThis() {
    console.log(this);
}
showThis(); // Window (non-strict) or undefined (strict)

3. Object Method

const person = {
    name: "Sudhanshu",
    greet: function() {
        console.log("Hello, " + this.name);
    }
};
person.greet(); // Hello, Sudhanshu

4. Constructor Function

function Person(name, age) {
    this.name = name;
    this.age = age;
}
const p1 = new Person("Sudhanshu", 21);
console.log(p1.name); // Sudhanshu

5. Arrow Function

const obj = {
    name: "Sudhanshu",
    greet: function() {
        const arrowFunc = () => console.log(this.name);
        arrowFunc();
    }
};
obj.greet(); // Sudhanshu

6. call, apply, bind

function sayHello(city) {
    console.log(`Hello, I am ${this.name} from ${city}`);
}
const person = { name: "Sudhanshu" };

sayHello.call(person, "Delhi");  // Hello, I am Sudhanshu from Delhi
sayHello.apply(person, ["Mumbai"]); // Hello, I am Sudhanshu from Mumbai
const boundFunc = sayHello.bind(person, "Kolkata");
boundFunc(); // Hello, I am Sudhanshu from Kolkata

Where this is Used

Summary