Skip to content

Commit 0cd73d1

Browse files
committed
More robust checking for global context and exports.
1 parent 63efc6a commit 0cd73d1

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

lib/core.js

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,7 @@ var INSTANCE = 0x2;
2626
// IE8 has a broken defineProperty but no defineProperties so this saves a try/catch.
2727
var PROPERTY_DESCRIPTOR_SUPPORT = !!(Object.defineProperty && Object.defineProperties);
2828

29-
// The global context. Rhino uses a different "global" keyword so
30-
// do an extra check to be sure that it's actually the global context.
31-
// istanbul ignore next
32-
var globalContext = typeof global !== 'undefined' && global.Object === Object ? global : this;
33-
34-
// Is the environment node?
35-
var hasExports = typeof module !== 'undefined' && module.exports;
29+
var globalContext = getGlobal();
3630

3731
// Whether object instance methods can be mapped to the prototype.
3832
var allowObjectPrototype = false;
@@ -53,6 +47,19 @@ var DefaultChainable = getNewChainableClass('Chainable');
5347

5448
// Global methods
5549

50+
function getGlobal() {
51+
// Get global context by keyword here to avoid issues with libraries
52+
// that can potentially alter this script's context object.
53+
return testGlobal(typeof global !== 'undefined' && global) ||
54+
testGlobal(typeof window !== 'undefined' && window);
55+
}
56+
57+
function testGlobal(obj) {
58+
// Note that Rhino uses a different "global" keyword so perform an
59+
// extra check here to ensure that it's actually the global object.
60+
return obj && obj.Object === Object ? obj : null;
61+
}
62+
5663
function setupGlobal() {
5764
Sugar = globalContext[SUGAR_GLOBAL];
5865
// istanbul ignore if
@@ -73,9 +80,11 @@ function setupGlobal() {
7380
return Sugar;
7481
};
7582
// istanbul ignore else
76-
if (hasExports) {
83+
if (typeof module !== 'undefined' && module.exports) {
84+
// Node or webpack environment
7785
module.exports = Sugar;
7886
} else {
87+
// Unwrapped browser environment
7988
try {
8089
globalContext[SUGAR_GLOBAL] = Sugar;
8190
} catch (e) {

0 commit comments

Comments
 (0)