Javascript - this execution context


In JavaScript, this is the current execution context of a function.

Let's take a look at what it means in the following scenarios:

Function Invocation

Invocation of the getContext() function will print the Window object.

That's because the context of the getContext() is Window/Global object.

At the time getContext() is called, JavaScript automatically sets this as the global object, which in a browser is Window.

function getContext() { 
    console.log(this); // Global or Window 

When this is used outside any function scope, it refers to the global scope.

if (this === window) { 
    console.log("this refers to the Global context"); 

If you're in strict mode ("use strict"), this would be undefined.

Method Invocation

Method invocation means an object's method is called and in this case, this is the object that owns the method in a method invocation.

let myObj = { 
    name: 'fancy', 
    operation: function() { 

myObj.operation(); // { name: 'fancy', operation: [Function: operation]} 

Method Invocation on calling myObj.operation(), [myObj object] will be printed in the console.

Consider the following code

let x = myObj.operation; 
x(); // Window 

Here, x refers to the operation() method inside [myObj object].

Calling x() would mean that we are making a function invocation instead of a method invocation and therefore, this will refer to the Global (or Window) object.

To call x with the [myObj object] (for method invocation), we will have to use .call() method:

let x = myObj.operation; 
x(); // Window; // { name: 'fancy', operation: [function]} 

Constructor Invocation

Constructor invocation happens when an object is created using the new keyword.

function Employee(name, department, salary) { = name; 
    this.department = department; 
    this.salary = salary; 

    console.log("Welcome " + + "!"); 

let john = new Employee('John', 'Sales', 4000); 
// Welcome John! 

new Employee('John', 'Sales', 4000) is a constructor invocation of the Employee function.

The result of execution is a new object and this refers to the newly created object.

Related Topic