This Binding in Node.js

In this article, we will explore the behavior of this in Node.js and how it changes depending where we use. You’ll learn how this works in different scenarios, such as in the global scope, inside functions, within arrow functions, and in classes through practical examples.

 

The behaviour of this in Node.js depends on where we use it, Now here below we’ll explore its usage in various scenarious

 

1.Global Scope

In Node.js, this in the Global scope refers to an empty object ({}) unlike global scope which refers to the global object in browers due to the module system.

Example:

console.log(this);

Output:

{}

In Node.js, this in the global scope refers to module.exports object which is initally empty as we can see in this example.

 

 2. this Inside Functions

The value of this regular function can be called in two ways and its value depends on how we call it, By default it well be in non-strict mode in it this refers to global object but in strict mode this is undefined

Example: this in Regular functions

function showThis() {
  console.log(this);
}

showThis();

Output:

global object (non-strict mode) or undefined (strict mode)

In this example this refers to the object that owns the method

Example: this in Methods

const obj = {
  name: 'Node.js',
  showThis: function () {
    console.log(this.name);
  },
};

obj.showThis();

Output:

Node.js

 

3. this Inside Arrow Functions

The Arrow functions do not have their own this but they can inherit this from their enclosing scope. This kind of behaviour can be very useful in cases like callbacks.

Example: 

const obj = {
  name: 'Node.js',
  showThis: function () {
    const arrowFunc = () => {
      console.log(this.name);
    };
    arrowFunc();
  },
};

obj.showThis();

Output:

Node.js

Here, this in the arrow function refers to the obj object because it inherts this from its neighboring methods

 

4. this in Classes

In Node.js classes, this refers to the instance of the class.

class Example {
  constructor(name) {
    this.name = name;
  }

  showThis() {
    console.log(this.name);
  }
}

const obj = new Example('Node.js');
obj.showThis();

Output:

Node.js

We may need to bind this explicitly to avoid losing its context, when using a method as a callback.

Example: Explicit Binding with .bind()

class Example {
  constructor(name) {
    this.name = name;
  }

  showThis() {
    console.log(this.name);
  }
}

const obj = new Example('Node.js');
setTimeout(obj.showThis.bind(obj), 1000);

Output:

Node.js

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top