globalThis icon indicating copy to clipboard operation
globalThis copied to clipboard

Slightly more horrifying, but more universal technique

Open mathiasbynens opened this issue 5 years ago • 2 comments

A horrifying globalThis polyfill in universal JavaScript describes a technique that could be useful for this project.

Instead of the current approach of detecting known environment-specific references to the global this, the new technique doesn't depend on any such bindings, and is 100% universal JavaScript (although you would still need a single fallback if IE <= 10 support is a concern).

mathiasbynens avatar Apr 18 '19 12:04 mathiasbynens

Modern implementation:

module.exports = () => {
	if (typeof globalThis === "object") {
		return globalThis
	}

	Object.defineProperty(Object.prototype, '__magic__', {
		get: function() {
			return this;
		},
		configurable: true
	});

	const result = __magic__;
	delete Object.prototype.__magic__;

	return result
}

Richienb avatar Aug 26 '20 15:08 Richienb

I see that the full approach has a fallback for window in IE < 11. Are there any non-browser engines that fail to work in the Object.defineProperty case?

If we have to rely on both window and Object.prototype anyways, i'm not sure if this (quite clever and indeed horrifying) approach is an improvement over the current implementation.

ljharb avatar Aug 27 '20 19:08 ljharb