global.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. var naiveFallback = function () {
  2. if (typeof self === "object" && self) return self;
  3. if (typeof window === "object" && window) return window;
  4. throw new Error("Unable to resolve global `this`");
  5. };
  6. module.exports = (function () {
  7. if (this) return this;
  8. // Unexpected strict mode (may happen if e.g. bundled into ESM module)
  9. // Fallback to standard globalThis if available
  10. if (typeof globalThis === "object" && globalThis) return globalThis;
  11. // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
  12. // In all ES5+ engines global object inherits from Object.prototype
  13. // (if you approached one that doesn't please report)
  14. try {
  15. Object.defineProperty(Object.prototype, "__global__", {
  16. get: function () { return this; },
  17. configurable: true
  18. });
  19. } catch (error) {
  20. // Unfortunate case of updates to Object.prototype being restricted
  21. // via preventExtensions, seal or freeze
  22. return naiveFallback();
  23. }
  24. try {
  25. // Safari case (window.__global__ works, but __global__ does not)
  26. if (!__global__) return naiveFallback();
  27. return __global__;
  28. } finally {
  29. delete Object.prototype.__global__;
  30. }
  31. })();