1. javascript
  2. /basics
  3. /this

The Basics of JavaScript `this`

What is this?

In JavaScript, this refers to the object that the current function or method is operating on. In other words, this is a reference to the object that invoked the function or method.

Consider the following code:

let obj = {
  name: "My Object",
  logName: function() {
    console.log(this.name);
  }
};

obj.logName(); // Output: "My Object"

The logName function is a method of the obj object. When we call obj.logName(), this inside the function refers to obj. Therefore, this.name is equivalent to obj.name, and the output is "My Object".

this is Different in JavaScript

The concept of this in JavaScript is similar to the self or this keyword in object-oriented languages. However, there are some key differences. In JavaScript, the value of this can change depending on how the function is invoked. In other languages, the value of this is determined by the class or object that the method belongs to.

The this Keyword in Different Contexts

The value of this in JavaScript can change based on how a function is invoked and in what context it is used.

Method Context

When a function is invoked as a method of an object, this refers to that object.

let greeting = {
  message: "Hello",
  showMessage: function() {
    console.log(this.message);
  }
};

greeting.showMessage(); // Output: "Hello"

In this example, the showMessage function is a method of the obj object. When we call obj.showMessage(), this inside the showMessage function refers to obj. Therefore, this.message is equivalent to obj.message, and the output is "Hello".

Constructor and Class Context

When a function is invoked as a class constructor or class method, this refers to the instance of the class.

class Greeting {
  constructor(message) {
    this.message = message;
  }

  showMessage() {
    console.log(this.message);
  }
}

let greeting = new Greeting("Hello");
greeting.showMessage(); // Output: "Hello"

In this example, when we create an instance of the Greeting class using the new keyword and invoke the showMessage method, this inside the method refers to the instance of the class, and this.message is equivalent to the message property of that instance.

Global Context

When we invoke a standalone function, this refers to the global object (window in the browser and global in Node.js). For example:

var message = "Global";

function showMessage() {
  console.log(this.message);
}

showMessage(); // Output: "Global"

Event Handlers with this

Event handlers in JavaScript also have special behavior when it comes to the this keyword. When an event handler is invoked, this refers to the element that the event was fired on.

For example:

let button = document.getElementById("myButton");
button.addEventListener("click", function() {
  console.log(this); // Output: <button id="myButton">
});

When the button is clicked, the event handler function is invoked, and this inside the function refers to the button element.

Using this in Strict Mode

In strict mode, certain features of JavaScript are altered to prevent errors and make the code more secure. In this section, we'll focus on some basic examples of how strict mode affects the use of this.

  • this inside a standalone function results in undefined instead of the global object
"use strict"
function logThis(){
  console.log(this)
}
logThis(); // Output: undefined
  • this in an arrow function cannot be modified using call, apply, or bind.
"use strict"
var obj = {
  message: "Hello",
  showMessage: () => {
    console.log(this.message);
  }
};
var message = "Global";
obj.showMessage.call({message: "Hello"}); // Output: "Global"
  • this inside a class constructor and class method refers to the instance of the class.
class MyClass {
  constructor(name) {
    this.name = name;
  }

  logName() {
    console.log(this.name);
  }
}
let myInstance = new MyClass("My Instance");
myInstance.logName(); // Output: "My Instance"

Conclusion

The this keyword in JavaScript is a potentially versatile tool. However, its behavior can be challenging to understand and predict, especially when working with nested functions, callbacks, and event handlers.

Specifically, "this" in JavaScript refers to the object from which a call originated. It is similar to the "self" or "this" keywords in object-oriented languages, but its value can change based on how the call was made as shown in the examples above. In other languages, the value is determined by the class or object to which the method belongs.

Therefore, a thorough understanding of the concept is much needed for a developer to write robust code and avoid common pitfalls.

We only covered the surface level and hopefully instilled confidence and motivation for you to deepen your knowledge further.

In summary:

  • The this keyword in JavaScript refers to the object that the current function or method is operating on.

  • The value of this can change depending on the context in which it is used, such as function context, object method context, constructor, and class context.

  • Strict mode alters the behavior of certain features of JavaScript to prevent errors and make the code more secure, affecting the usage of this in certain contexts, such as standalone functions and arrow functions.

  • It's crucial to understand how this works in both strict and non-strict mode, especially when working with arrow functions, class constructors, and class methods, as this will ensure that your code is more maintainable and less prone to bugs.