Explain this keyword in JS with examples

Hello everyone, In this article, we are going to discuss ‘this’ keyword in Javascript(JS). The this keyword is one of the most widely used keywords. It can seem complex & difficult to understand at first, but once you start using the “this” keyword, everything will become straightforward and easy.

The “this” keyword in JavaScript(JS) is a reserved keyword meant to help you target certain objects in JavaScript. To be more specific, it’s meant to help you target the current object.

The main purpose of this keyword is to give methods access to their objects to perform some actions and to make our code reusable by allowing us to execute the same code for multiple objects.

Let’s understand it better in detail by taking an example.

What is the ‘this’ keyword?

If we used the ‘this’ keyword in the function, then it means it points to an object to which it is bound. In other words, this references the object currently calling the function. The value of this is the window object.

// output: Window { …}console.log(this)

For example,

let counter = {
count: 0,
show: function () {
return ++this.count;
},
};
counter.show();

In the above code, this references the counter object. The show() function is the property of the counter object. Therefore, inside the show() function, this references the counter object.

Types of Binding in Javascript

There are various ways that can be used to know which object is referred to by this keyword.

In this context, variables are declared outside the function. Here, this keyword refers to the window object.

var name = 'Javascript';function getName() {
console.log(this.name);
}
getName();/* Output: Javascript */

This rule, however, doesn’t hold if getName() were to be defined in strict mode:

var name = 'Javascript';function getName() {
'use strict';
console.log(this.name);
}
getName();/* Output: TypeError: `this` is `undefined` */

When set in strict mode, this reference is set to undefined.

It is applied when you call a function using the object and dot notation. In this case, this keyword points out the object, that is used to call the function.

// function is defined
function getName() {
console.log(this)
}
const obj = {
count: 4,
getName: getName,
}
// function is called using obj
obj.getName(); // count = 4

We can also call the function using the nested objects. See the below example:

function getName() {
console.log(this.count)
}
const obj = {
count: 4,
getName: getName,
nestedObj: {
count: 6,
getName: getName
}
}
obj.nestedObj.getName(); // count = 6

We saw in the Implicit Binding, that this is implicitly bound to the object the function is being called from. But in Explicit, we pressurized the function to use the particular object as its context.

We can achieve this by using two methods call() & apply(). These two utility methods are available to all the functions in Javascript.

Call():

function alert() { 
console.log(this.count + ' number');
}
const myObj = {
count: 4
}
alert.call(myObj); // 4 number

Apply():

const person = {
name: "John",
age: 18,
}
function getPerson(params) {
/* output: John is not available today. */
console.log(`${this.name} is ${params[0]} ${params[1]}`)
}
getPerson.apply(person, ["not available", "today"])

So, you have to invoke the call(), apply() on that function, and pass the context object as the parameter.

Note: If you pass the same function around multiple times to new variables. On every call, it will use the same context because it has been locked (explicitly bound) to that object. This is called Hard Binding.

When you use the new keyword to create an instance of a function object, you use the function as a constructor. The following things can happen:

  • Creation of a new object.
  • A newly constructed object is linked to the function that constructed it.
  • The constructed object is set as this binding to that function call.

Understand it better with the example:

function setCount(age) { 
this.count = count;
}
const num = new setCount(4);
console.log(num.count); // 4

Summary

So, to wrap up all the points:

  • this keyword, when used in a function, binds that function to a context object.
  • There are four types of binding: Default, Implicit, Explicit, and Constructor call (new).
  • The behavior of this keyword changes between strict and non-strict modes.

These rules will help you easily catch the context for this reference.

So, we learned about this keyword in Javascript(JS), and how you can use it to refer to any object in multiple ways. With this, we have come to the end of our article. I hope you understood what is this keyword and how they are used.

For more such content keep following and subscribing to this page. Please reach out to us in the comment section or drop us an email here, and I will surely help you in clearing doubts.

Thanks, Happy Learning.

Also, read

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Siddharth Rastogi

I am a full stack developer, I have an expertise in Web Development. I write tech stuff and share my knowledge with others with the help of articles.