es-shims / globalThis

ECMAScript spec-compliant polyfill/shim for `globalThis`.
https://github.com/tc39/proposal-global
MIT License
155 stars 14 forks source link

Slightly more horrifying, but more universal technique #3

Open mathiasbynens opened 5 years ago

mathiasbynens commented 5 years ago

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).

Richienb commented 4 years ago

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
}
ljharb commented 4 years ago

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.