DEV Community

Yu Hamada
Yu Hamada

Posted on

What is ”this” in JavaScript?

Table of Contents

  1. What is this?
    • this in a Method
    • this When Used Alone
    • this in Functions
    • this in Event Handlers
    • Controlling this with call() and apply()
    • this in Arrow Functions
  2. Conclusion

What is "this"?

In JavaScript, this is a keyword that refers to the object it belongs to. It has different objects depending on where it's used.

this in a Method.

Example: If you have an object person with a method getName, this inside getName refers to person.
In a method, this refers to the owner object.

const person = {
  name: 'Alice',
  getName: function() {
    return this.name;  // 'this' refers to 'person'
  }
};

Enter fullscreen mode Exit fullscreen mode

this When Used Alone

In a browser, it's window in Node.js, it's global. However, in strict mode ('use strict'), this will be undefined if it's not part of an object.
this refers to the global object.

console.log(this);  // Logs 'window' in a browser
Enter fullscreen mode Exit fullscreen mode

this in Functions

This is similar to when this is used alone, but in strict mode, this will be undefined.
In a function, this refers to the global object.

function show() {
  console.log(this);  // 'this' is 'window' in non-strict mode
}

Enter fullscreen mode Exit fullscreen mode

this in Event Handlers

Example: If a button in the HTML receives a click event, this inside the event handler refers to that button.
In an event, this refers to the element that received the event.

button.addEventListener('click', function() {
  console.log(this);  // 'this' refers to 'button'
});
Enter fullscreen mode Exit fullscreen mode

Controlling this with call() and apply()

These methods call a function with a specified this value and arguments, allowing you to control the execution context.
With call() and apply(), you can specify the value of this.

function greet() {
  console.log(`Hello, ${this.name}`);
}

const person = {name: 'Alice'};
greet.call(person);  // 'this' in greet() is set to 'person'
Enter fullscreen mode Exit fullscreen mode

this in Arrow Functions

Arrow functions do not have their own this context; instead, this is the same as in the enclosing lexical context.
In arrow functions, this is lexically inherited from the enclosing scope.

const person = {
  name: 'Alice',
  greet: () => {
    console.log(this.name);  // 'this' is the same as it was outside the arrow function
  }
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

The behavior of this can be confusing due to its different values in different contexts, making it important to understand where and how this is being used in your code.

Top comments (0)