Skip to content

Instantly share code, notes, and snippets.

@dwelch2344
Created July 9, 2024 15:56
Show Gist options
  • Save dwelch2344/22c47f4a23257c796b874778bb3f087b to your computer and use it in GitHub Desktop.
Save dwelch2344/22c47f4a23257c796b874778bb3f087b to your computer and use it in GitHub Desktop.
(function() {
if (typeof globalThis === 'object') return;
try {
// This will define globalThis as a getter on the global object
Object.defineProperty(Object.prototype, '__magic__', {
get: function() {
return this;
},
configurable: true // This makes it possible to delete the property later.
});
__magic__.globalThis = __magic__; // `this` is the global object in a non-strict mode function.
delete Object.prototype.__magic__;
} catch (e) {
// In environments where `Object.defineProperty` is not available,
// you can fallback to the more traditional but less correct implementations.
if (typeof self !== 'undefined') {
self.globalThis = self;
} else if (typeof window !== 'undefined') {
window.globalThis = window;
} else if (typeof global !== 'undefined') {
global.globalThis = global;
} else {
throw new Error('globalThis is not polyfillable in this environment.');
}
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment