DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 11: This

What is this?

In JavaScript, this is a special keyword that refers to the context in which a function is executed. The value of this is determined dynamically based on how a function is called, rather than how it is defined. The context can be the global object, the object that owns the method being invoked, or even explicitly set using call, apply, or bind.

Understanding this in Different Contexts:

Global Context:

When this is referenced in the global scope (outside any function or object), it refers to the global object. In browsers, the global object is the window object.

console.log(this === window); // Output: true
Enter fullscreen mode Exit fullscreen mode

Function Context:

When this is used within a regular function, its value depends on how the function is called.

function sayHello() {
  console.log(this);
}

sayHello(); // Output: window (in non-strict mode), undefined (in strict mode)
Enter fullscreen mode Exit fullscreen mode

Method Context:

When this is used inside an object's method, it refers to the object itself.

const person = {
  name: 'John',
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

person.greet(); // Output: Hello, my name is John
Enter fullscreen mode Exit fullscreen mode

Strict Mode:

In JavaScript strict mode, the value of this is not automatically coerced to the global object when calling a function in the global scope. Instead, it remains undefined.

'use strict';

function showThis() {
  console.log(this);
}

showThis(); // Output: undefined
Enter fullscreen mode Exit fullscreen mode

Arrow Functions:

Arrow functions do not have their own this binding. Instead, they inherit the this value from the surrounding lexical scope. This behavior makes arrow functions particularly useful in callback functions or when you want to preserve the this context.

const person = {
  name: 'Alice',
  greet: function() {
    const innerFunc = () => {
      console.log(`Hello, I'm ${this.name}`);
    };
    innerFunc();
  }
};

person.greet(); // Output: Hello, I'm Alice
Enter fullscreen mode Exit fullscreen mode

Summary

  • Global Context: this refers to the global object.
  • Function Context: this refers to the global object in non-strict mode. In strict mode, it is undefined.
  • Method Context: this refers to the object the method is called on.
  • Arrow Functions: this is inherited from the surrounding context and is not bound to the function.

Top comments (0)