A Foolproof Guide To 'this' In JavaScript
Tags: javascript, webdev, programming
Published: 2023-01-10 11:32:31

##Introduction

JavaScript's `this` keyword can be a source of confusion for many developers, especially when working with event handlers, callbacks, and other complex scenarios. Understanding how `this` works in JavaScript is crucial for writing efficient and maintainable code.

<!--truncate-->

In this article, we will go over the various ways in which `this` is determined in JavaScript, and provide a foolproof guide for understanding and using `this` in your code.

## How `this` is determined

JavaScript's `this` keyword refers to the object that the code is currently executing within. The value of `this` is determined by how the function is called, rather than where it is defined, which is known as `implicit binding` or `runtime/late binding`. In other words, `this` is determined at the time the function is invoked and not when it is defined.

## `this` as a method of an object

The first way in which `this` is determined is when a function is invoked as a method of an object. For example:

```js
const obj = {
	name: 'Mark',
	sayHi: function () {
		console.log(`Hi, my name is ${this.name}`);
	},
};

obj.sayHi(); // Output: "Hi, my name is Mark"
```

In this example, `this` inside the `sayHi` function refers to the `obj` object, because the function is invoked as a method of `obj`.

## `this` as a standalone function

When a function is invoked as a standalone function, `this` is set to the global object (or undefined in strict mode). For example:

```js
function sayHi() {
	console.log(`Hi, my name is ${this.name}`);
}

sayHi(); // Output: "Hi, my name is undefined"
```

In this case, `this` inside the `sayHi` function refers to the global object.

## Explicitly setting the value of `this`

Another way to set the value of `this` is by using the `call` or `apply` methods. These methods allow you to explicitly set the value of `this` when calling a function. For example:

```js
const person = { name: 'Mark' };

function sayHi() {
	console.log(`Hi, my name is ${this.name}`);
}

sayHi.call(person); // Output: "Hi, my name is Mark"
```

In this example, `this` inside the `sayHi` function is set to the `person` object using the `call` method.

## `this` as a constructor

When a function is invoked as a constructor, `this` is set to the newly created object. For example:

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

const person = new Person('Mark');
console.log(person.name); // Output: "Mark"
```

In this case, `this` inside the `Person` function refers to the new object that is created when the function is invoked with the `new` keyword.

## Function binding techniques

In addition, In JavaScript, the value of `this` is determined at runtime and it can change based on how the function is invoked. This is where it can get a little tricky to understand, especially when working with event handlers and callback functions, because the value of "this" may not be what you expect. To tackle this problem, you can use function binding techniques like `.bind()`, `.call()` and `.apply()` to ensure that `this` refers to the correct object.

## Arrow functions and `this`

The last way `this` is determined is when a function is defined as an arrow function. Arrow functions do not have their own `this` scope and it will inherit `this` from its parent scope. This is useful when you need to preserve the value of `this` from the surrounding code. For example:

```js
const person = {
	name: 'Mark',
	sayHi: () => {
		console.log(`Hi, my name is ${this.name}`);
	},
};

person.sayHi(); // Output: "Hi, my name is Mark"
```

In this example, the arrow function preserves the `this` context of the parent scope, which is the `person` object, as opposed to the global object or undefined.

## Using the `bind` method

It's also important to note that in some cases, `this` can be set using the `bind` method to create a new function with a specific context, this method can be useful when you want to pass a function as a callback and maintain the context.

```js
const person = { name: 'Mark' };
const sayHi = function () {
	console.log(`Hi, my name is ${this.name}`);
}.bind(person);

setTimeout(sayHi, 1000);
```

In this example, `this` inside the `sayHi` function will always refer to the `person` object, even when it's passed as a callback to the `setTimeout` function.

> In conclusion, understanding how `this` works in JavaScript is crucial to writing efficient and maintainable code. By understanding how its value is determined, you can use function binding techniques and arrow functions to ensure that `this` refers to the correct object in your code. It's important to keep in mind that this may not have the expected value in certain situations, and by using the binding methods and arrow functions you can maintain the context of the `this` keyword.

Keep building! 🚀