# unicorn/prefer-global-this

> Require `globalThis` instead of `window`, `self` and `global`

A worker has no `window`, a browser has no `global`, and Node.js has no `self`. Code that names one of them throws a `ReferenceError` where it doesn't exist. `globalThis` is the same object and exists everywhere.

Properties that only make sense on one of them are allowed, such as `window.innerWidth`, `window.addEventListener("resize", ...)` and `self.postMessage()`. Computed access such as `window[name]` is allowed too, and so is your own variable with one of these names.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

```toml bunfig.toml
[lint.rules]
"unicorn/prefer-global-this" = "error" # or "warn"
```

{/* End of the generated section. */}

## Examples

Reported:

{/* bad {"count": 3} */}
```js
global.cache = new Map();
window.setTimeout(refresh, 1000);

if (typeof window !== "undefined") {
  start();
}
```

Not reported:

{/* good */}
```js
globalThis.cache = new Map();
globalThis.setTimeout(refresh, 1000);

if (typeof globalThis.window !== "undefined") {
  start();
}
```

{/* good */}
```js
const width = window.innerWidth;
window.addEventListener("resize", layout);
self.postMessage({ done: true });
const handler = window[name];
```

An event that isn't specific to the window is reported:

{/* bad */}
```js
window.addEventListener("click", close);
```
