I want to check in a script if a certain other module is already loaded.
if (ModuleName) {
// extend this module
}
But if ModuleName doesn’t exist, that throws.
If I knew what the Global Object was I could use that.
if (window.ModuleName) {
// extend this module
}
But since I want my module to work with both browsers and node, rhino, etc., I can’t assume window.
As I understand it, this doesn’t work in ES 5 with "use strict";
var MyGLOBAL = (function () {return this;}()); // MyGlobal becomes null
This will also fail with a thrown exception
var MyGLOBAL = window || GLOBAL
So it seems like I’m left with
try {
// Extend ModuleName
}
catch(ignore) {
}
None of these cases will pass JSLint.
Am I missing anything?
Well, you can use the
typeofoperator, and if the identifier doesn’t exist in any place of the scope chain, it will not throw aReferenceError, it will just return"undefined":Remember also that the
thisvalue on Global code, refers to the global object, meaning that if yourifstatement is on the global context, you can simply checkthis.ModuleName.About the
(function () { return this; }());technique, you are right, on strict mode thethisvalue will simply beundefined.Under strict mode there are two ways to get a reference to the Global object, no matter where you are:
Through the
Functionconstructor:Functions created with the
Functionconstructor don’t inherit the strictness of the caller, they are strict only if they start their body with the'use strict'directive, otherwise they are non-strict.This method is compatible with any ES3 implementation.
Through an indirect
evalcall, for example:The above will work because in ES5, indirect calls to
eval, use the global environment as both, the variable environment and lexical environment for the eval code.See details on Entering Eval Code, Step 1.
But be aware that the last solution will not work on ES3 implementations, because an indirect call to
evalon ES3 will use the variable and lexical environments of the caller as the environments for the eval code itself.And at last, you may find useful to detect if strict mode is supported: