Global variables and JavaScript modules

Or how to load a library as a module when it is not released as a module.

Marian C.
CodeX

--

A window borrowed from https://creazilla.com/nodes/78602-window-clipart

About the Window object

In a web browser, Window is an object whose properties are accessible from any scope of any script of a web page.

In classic scripts, Window can accessed in several ways:

  • Using window or self properties of the Window
  • Using this keyword outside a method
  • Using globalThis keyword

In modules, this never refers to the Window. Outside a method this value is undefined.

Let’s demonstrate that using a simple script:

//windows.js
console.log( document.currentScript ? 'classic' : 'module' );
console.log('window='+ window);
console.log('self=' + self, window === self);
console.log('this=' + this, window === this);
console.log('globalThis=' + globalThis, window === globalThis);

The first statement of the script window.js prints how the script is executed — as a classic script or as a module. Then the following statements print values of window, self, this and globalThis and test their equality with window.

--

--

Marian C.
CodeX
Writer for

Java, JavaScript and SQL developer. Interested in data collection and visualization.