Advance JavaScript (DOM, BOM, Web API) / Object Oriented Programming

this keyword

In JavaScript, the this keyword is a fundamental concept that refers to the object it belongs to. Its value depends on the context in which it is used. Here’s a detailed explanation of how this works in different contexts:

1. Global Context

In the global execution context (outside of any function), this refers to the global object:

  • In a browser, it’s window.

  • In Node.js, it’s global.

console.log(this); // In a browser, it logs `window`

2. Function Context

In a regular function, the value of this depends on how the function is called.

  • Simple Function Call: this refers to the global object (or undefined in strict mode).

    function show() {
        console.log(this); 
    }
    show();
    // Logs `window` in non-strict mode, `undefined` in strict mode
  • Method Call: When a function is called as a method of an object, this refers to the object the method is called on.

    const person = {
        name: 'Alice',
        greet() {
            console.log(this); 
            // Logs `person` object
        }
    };
    person.greet();

3. Constructor Function

When a function is used as a constructor with the new keyword, this refers to the newly created instance.

function Person(name) {
    this.name = name;
}

const john = new Person('John');
console.log(john.name); // Logs 'John'

4. Arrow Functions

Arrow functions do not have their own this. Instead, they inherit this from the enclosing lexical context (the function or block they are defined in).

const person = {
    name: 'Alice',
    greet: function() {
        const innerFunc = () => {
            console.log(this); // Logs `person` object
        };
        innerFunc();
    }
};
person.greet();

5. call, apply, and bind Methods

These methods allow explicitly setting the value of this.

  • call and apply: Immediately invoke the function with a specified this value.

    function greet() {
        console.log(this.name);
    }
    
    const person = { name: 'Alice' };
    
    greet.call(person);  // Logs 'Alice'
    greet.apply(person); // Logs 'Alice'
  • bind: Returns a new function, permanently setting this to the provided value.

    const boundGreet = greet.bind(person);
    boundGreet(); // Logs 'Alice'

6. Event Handlers

In event handlers, this refers to the element that received the event.

document.getElementById('myButton').addEventListener('click', function() {
    console.log(this); // Logs the button element
});

Summary Table

Context

this Value

Global

Global object (window/global)

Function (non-strict mode)

Global object (window/global)

Function (strict mode)

undefined

Method of an object

The object itself

Constructor function

The newly created instance

Arrow function

Lexical context this

call/apply/bind

Explicitly specified object

Event handler

The element receiving the event

Understanding the behavior of this is crucial for writing effective and bug-free JavaScript code, especially when working with object-oriented programming and event handling.