Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 133 ยท Getting Started

this Binding and Module-Level State in Node

Understand what this means in Node.js modules, functions, methods and event listeners, fix lost this with bind, call and arrow functions, and avoid shared module state leaking between requests.

Two questions cause a surprising share of confusing Node.js bugs. The first is "what is this right now?" The second is "who else can see this variable?" They are related: both are about where a value lives and who can reach it. In a browser script most of your variables are global and this at the top is the window. Node is different, and knowing how will save you hours.

This lesson explains what this is at the top of a module, inside functions, methods, callbacks and event listeners, how to fix a lost this, and how module-level variables behave when many requests share one process.

this at the top of a file

Every file in Node is a module with its own scope. What this is at the top level depends on the module system:

  • In an ES module (.mjs, or .js with "type": "module"), top-level this is undefined.
  • In a CommonJS module (.cjs, or .js without "type": "module"), top-level this is module.exports, an empty object at the start.

This is not the same as the browser, where top-level this is window. And because every file is wrapped in its own scope, a var or function at the top of a Node file does not become a global.

Node.js this at the top level of an ES module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The same code in a CommonJS file behaves differently at the top level. Start a TryIt with the line // cjs and the editor runs it as CommonJS:

Node.js this at the top level of a CommonJS module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the last line: in a CommonJS file a plain function called with no object gets globalThis as this, unless the file has 'use strict'. In an ES module the code is always strict, so plain() returns undefined. That is one more reason to prefer ES modules.

How a function gets its this

For regular functions, this is decided by how the function is called, not where it is written:

Call this
obj.method() obj
method() (plain call) undefined in strict mode, globalThis in sloppy mode
new Thing() the new object
fn.call(x, ...), fn.apply(x, [...]), fn.bind(x) x
Arrow function whatever this was where the arrow was written

An arrow function has no this of its own; it uses the surrounding one. That makes arrows ideal for callbacks inside methods, and a bad choice for object methods that need their own this.

Node.js Losing this, and three ways to keep it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The class method lost its this because loose() is a plain call, and class bodies are always strict, so this is undefined and this.count++ throws a TypeError. The three fixes are standard: bind makes a new function with a fixed this, call and apply set it for one call (they differ only in passing arguments one by one or as an array), and an arrow wrapper makes the call look like c.increment() again. A class field holding an arrow function binds once per instance, which costs a little memory per object but is handy for handlers.

this inside Node callbacks

Node's own APIs call your function in different ways, so this differs:

  • EventEmitter listeners written as regular functions get this set to the emitter. Arrow functions do not; they keep the outer this.
  • Timers call your function with a Timeout object as this when it is a regular function. Never rely on it.
  • Promise callbacks and await do not change this: inside an arrow function it is still the outer one.
Node.js this inside event listeners

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The rule of thumb: inside a class, register listeners with arrow functions so this is your object. When you need the emitter itself, use a regular function or just use the variable that holds it.

Module-level state is shared state

A module is loaded and run once per process, then cached. Every file that imports it receives the same exports, and a variable declared at the top of the module exists once and is shared by everyone. That is perfect for configuration, a database pool or a cache. It is dangerous for anything that belongs to a single user or request, because a web server handles many requests at the same time in one process.

Node.js Module state is shared by every request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Ana's greeting says "hello Ben" in the bad version: both requests wrote to the same variable, and the slow one read it back after the fast one had overwritten it. No threads are involved; the interleaving happens at every await or timer. The fixes:

  • Keep per-request data in local variables or on the req/res objects (req.user = user in a middleware). Each request has its own.
  • For data you must reach from deep inside call stacks without passing it around (request ids for logs), use AsyncLocalStorage, shown above as requestStore.
  • Keep module-level state read-only or clearly process-wide: configuration, constants, caches with a size limit, connection pools.

Also remember that module state is per process. With cluster mode or several containers, each process has its own copy, so a counter or "session variables" stored in a module-level object differ between instances and vanish on every restart. Data that must outlive a request or be shared between servers (user sessions, shopping carts, rate-limit counters) belongs in a store such as Redis or a database; see Sessions and JWT.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is this at the top level of an ES module?

    ES modules are strict and have no this binding at the top level, so it is undefined. In CommonJS it is module.exports.
  2. 2. A class method is passed as a callback, setTimeout(counter.increment, 10), and throws when it reads this.count. Which change fixes it?

    The method was called without its object, so this was undefined. bind (or a wrapper that calls counter.increment()) restores the connection.
  3. 3. Which statement about arrow functions and this is true?

    Arrow functions have no own this; they capture the surrounding one, and call, apply and bind cannot change it.
  4. 4. Why is a module-level let currentUser a bad way to remember the user of a request in a web server?

    Every await or timer lets another request run. They all share the one variable, so one request can read another's value. Use locals, req properties or AsyncLocalStorage.
  5. 5. Where should data that must be shared between several Node.js server instances live?

    Each process has its own module state, and it disappears on restart. Shared state belongs in an external store.

Summary

  • Every file is a module with its own scope. Top-level this is undefined in ES modules and module.exports in CommonJS; var at the top does not create a global.
  • For regular functions this depends on the call: obj.method(), plain call, new, call/apply/bind. Arrow functions keep the outer this.
  • A method detached from its object loses this; fix with bind, a wrapper arrow, or an arrow class field.
  • Emitter listeners written as regular functions get the emitter as this; arrows do not.
  • Module-level variables are shared by all requests in a process, so keep them read-only or process-wide. Per-request data goes in locals, req or AsyncLocalStorage.
  • Data shared across processes or restarts belongs in a database or cache, not in module memory.

Next: ES Modules