'this' keyword in JavaScript

Jessica Mishra
Last Updated: May 13, 2022

Introduction

JavaScript has a 'this' keyword. Just like other languages, it points to the object it belongs to. But it behaves a little differently as compared to other languages.

Let us discuss 'this' keyword in JavaScript.

this keyword in JavaScript

The value of 'this' is determined by how a function was called during runtime. We cannot assign any particular value to it, and it may be different each time the function is executed. Let us look at the usage of the 'this' keyword in JavaScript.

 

Code:

const test = {
  prop: 10,
  func: function() {
    // Here 'this' refers to the owner object
    return this.prop;
  },
};

console.log(test.func());

 

Output:

10

Global Context

In the context of global education, 'this' keyword in JavaScript points to the global object in both strict and non-strict mode. 

The window object is the global object.

 

Code:

// Here 'this' refers to global or window object
this.color= 'Red';
console.log(window.color); // Red Color

 

Output:

"Red"

 

The property assigned to this object in the global context is added to the property of the global object, i.e., the window object.

Function Context

Inside a function, the value of 'this' keyword in JavaScript depends on how the function is called.

In non-strict mode

Here, 'this' refers to the global object, the window object.

 

Code:

function show() {
  // Here 'this' refers to the window object
  console.log(this === window); // True
}

show();

 

Output:

True

In strict mode

Here, the 'this' object is set to undefined in the strict mode. 

Code:

"use strict"; // Setting the strict mode

function show() {
    console.log(this === undefined); // True
}

show();

 

Output:

True

Method Invocation

When the method of an object is called, 'this' keyword in JavaScript is set to the object owning the method. 

 

Code:

let student = { // Class
    name: 'Ninja',
    getname: function () {
        // Here 'this' refers to owner object
        return this.name;
    }
}

console.log(student.getname()); // Method

 

Output:

Ninja

 

Let us look at another example:

Code:

let blog = {
    name: 'Coding Ninja',
    getName: function() {
        console.log(this.name);
    }
};

setTimeout(blog.getName, 1000);

 

Output:

Undefined

 

'Undefined' is printed instead of 'Coding Ninja' as the method is called without specifying the object.

To remove this, we can use a bind() method:

let functionBind = blog.getName.bind(blog);
setTimeout(functionBind, 1000);

 

Output:

Coding Ninja

 

bind() method creates a new function whose 'this' keyword is set to a specified value. 

Constructor Invocation

The function can be used as a constructor when creating an instance of a function object. Here, the 'this' keyword is assigned to the newly created object. 

 

Code:

function Student(name) {
    this.name = name;
}

Student.prototype.getName = function () {
    // Here 'this' refers to function object
    return this.name;
}

var student = new Student('Ninja');
console.log(student.getName());

 

Output:

Ninja

 

We can see that the 'this' keyword in JavaScript is assigned to the newly created object. 

Indirect Invocation

In Javascript, function objects are instances of the Function type. The Function type has two methods: call() and apply(). We can set the value of 'this' keyword in JavaScript while calling the function using these methods.

 

Code:

function getName(prefix) {
    // Here 'this' refers to function object
    console.log(prefix + this.name);
}

let john = {
    name: 'John'
};
let stacey = {
    name: 'Stacey'
};

getName.call(john, "I am ");
getName.call(stacey, "My name is ");

 

Output:

I am John
My name is Stacey

 

In the above example, the getName() function was called indirectly using the call() method of the getName function.

The apply() method is very similar to the call() method. The second argument is passed as an array of arguments:

getName.apply(john, ["I am "]); 
getName.apply(stacey, ["My name is "]); 

 

The output would be the same.

Arrow Functions

Using arrow functions, the value of this can be set lexically. This means that the arrow function inherits 'this' from the outer functions containing the arrow function.

 

Code:

let getThis = () => this;
console.log(getThis() === window); 

 

Output:

True 

 

To summarize, when 'this' keyword in JavaScript is used:

In

Refers to

method

Owner object

Alone

Global object

function

Global object

function(strict) 

undefined

Event handlers

An element receiving the event

 

Frequently Asked Questions

1. What is the precedence order of 'this' keyword?

Ans: The precedence of order of 'this' keyword is:

  1. bind() method
  2. call() and apply() method
  3. Object's method
  4. Global scope

 

2. Explain call() and apply() method.

Ans: A function in JavaScript can be called using the () operator, as well as the call() and apply() methods, as given in the example below.

function printName() {
   alert('Coding Ninjas');
}

printName.call();
printName.apply();

 

Output

The alert message pops up two times since we have both used call() and apply() methods.

printName(), printName.call(), and printName.apply() functions perform the same action in the example above.

The fundamental purpose of the call() and apply() is to set the context of 'this' inside a function, regardless of whether it is called in the global scope or as an object's method.

 

3. What is the difference between implicit and explicit 'this' binding?

Ans: Implicit binding occurs when a dot notation is used to invoke the function and whatever is to the left of the dot becomes the context for 'this' in the function.

Explicit binding of 'this' occurs when .call(), .apply(), or .bind() are used on a function.

 

4. What does 'this' refer to in event handlers?

Ans: In HTML event handlers, 'this' refers to the HTML element that received the event.

Key Takeaways

In this blog, we learned about the behavior of 'this' keyword in JavaScript in different contexts.

To learn more about programming in JavaScript, check out the JavaScript-guided path. If you are preparing for your next web development interview, check out the blogs, 25 CSS Interview Questions, and 30 JavaScript interview questions.

Credits: GIPHY

Happy Coding!

Was this article helpful ?
0 upvotes