Skip to content

Latest commit

 

History

History
76 lines (56 loc) · 1.88 KB

prefer-global-this.md

File metadata and controls

76 lines (56 loc) · 1.88 KB

Prefer globalThis over window, self, and global

💼 This rule is enabled in the ✅ recommended config.

🔧 This rule is automatically fixable by the --fix CLI option.

This rule will enforce the use of globalThis over window, self, and global.

However, there are several exceptions that remain permitted:

  1. Certain window/WebWorker-specific APIs, such as window.innerHeight and self.postMessage
  2. Window-specific events, such as window.addEventListener('resize')

The complete list of permitted APIs can be found in the rule's source code.

Examples

window; // ❌
globalThis; // ✅
window.foo; // ❌
globalThis.foo; // ✅
window[foo]; // ❌
globalThis[foo]; // ✅
global; // ❌
globalThis; // ✅
global.foo; // ❌
globalThis.foo; // ✅
const {foo} = window; // ❌
const {foo} = globalThis; // ✅
window.location; // ❌
globalThis.location; // ✅

window.innerWidth; // ✅ (Window specific API)
window.innerHeight; // ✅ (Window specific API)
window.navigator; // ❌
globalThis.navigator; // ✅
self.postMessage('Hello'); // ✅ (Web Worker specific API)
self.onmessage = () => {}; // ✅ (Web Worker specific API)
window.addEventListener('click', () => {}); // ❌
globalThis.addEventListener('click', () => {}); // ✅

window.addEventListener('resize', () => {}); // ✅ (Window specific event)
window.addEventListener('load', () => {}); // ✅ (Window specific event)
window.addEventListener('unload', () => {}); // ✅ (Window specific event)