Videos
In Chrome, go to Dev tools and open the console. Then type in the following:
Object.keys( window );
This will give you an Array of all the global variables.
After searching on Google a bit, I found a way. You will need Firefox and the jslinter addon.
Once setup, open jslinter and go to Options->check everything on the left column except "tolerate unused parameters".
Then run jslinter on the webpage and scroll down in the results. You will have a list of unused variables (global and then local to each function).
Now run Object.keys(window); in the console and compare the results from both to figure out which ones are used.
This one-liner will get you pretty close, and does not require installing anything additional, or running code before the page loads:
Object.keys(window).filter(x => typeof(window[x]) !== 'function' &&
Object.entries(
Object.getOwnPropertyDescriptor(window, x)).filter(e =>
['value', 'writable', 'enumerable', 'configurable'].includes(e[0]) && e[1]
).length === 4)
It filters Object.keys(window) based on three principles:
- Things that are null or undefined are usually not interesting to look at.
- Most scripts will define a bunch of event handlers (i.e. functions) but they are also usually not interesting to dump out.
- Properties on window that are set by the browser itself, are usually defined in a special way, and their property descriptors reflect that. Globals defined with the assignment operator (i.e.
window.foo = 'bar') have a specific-looking property descriptor, and we can leverage that. Note, if the script defines properties using Object.defineProperty with a different descriptor, we'll miss them, but this is very rare in practice.
Well, you can use the typeof operator, and if the identifier doesn't exist in any place of the scope chain, it will not throw a ReferenceError, it will just return "undefined":
if (typeof ModuleName != 'undefined') {
//...
}
Remember also that the this value on Global code, refers to the global object, meaning that if your if statement is on the global context, you can simply check this.ModuleName.
About the (function () { return this; }()); technique, you are right, on strict mode the this value will simply be undefined.
Under strict mode there are two ways to get a reference to the Global object, no matter where you are:
Through the
Functionconstructor:var global = Function('return this')();
Functions created with the Function constructor 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:"use strict"; var get = eval; var global = get("this");
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 eval on 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:
var isStrictSupported = (function () { "use strict"; return !this; })();
Update 2019
With all of today's Webpacks and Broccolis, and Gulps and Grunts, and TypeScripts and AltScripts, and create-react-apps, etc, this is pretty useless, but if you're just working with plain, old, VanillaJS and you want to make it isomorphic, this is probably your best option:
var global
try {
global = Function('return this')();
} catch(e) {
global = window;
}
The Function constructor invocation will work even when using --use_strict in node, as the Function constructor always executes in a global non-strict scope.
If the Function constructor fails, it's because you're in a browser with eval disabled by CSP headers.
Of course, with Deno on the way (the node replacement), they may also disallow the Function constructor, in which case it's back to enumerating objects like global, module, exports, globalThis and window, and then duck-type checking which is the global exhaustively... :-/
Crazy one-line solution (Original):
var global = Function('return this')() || (42, eval)('this');
.
.
.
Works
- in every environment (that I tested)
- in strict mode
- and even in a nested scope
Update 2014-Sept-23
This can now fail if HTTP headers in the latest browsers explicitly forbid eval.
A workaround would be to try / catch the original solution as only browsers are known to run this type of subset of JavaScript.
var global;
try {
global = Function('return this')() || (42, eval)('this');
} catch(e) {
global = window;
}
Example:
---
(function () {
var global = Function('return this')() || (42, eval)('this');
console.log(global);
// es3 context is `global`, es5 is `null`
(function () {
"use strict";
var global = Function('return this')() || (42, eval)('this');
console.log(global);
}());
// es3 and es5 context is 'someNewContext'
(function () {
var global = Function('return this')() || (42, eval)('this');
console.log(global);
}).call('someNewContext');
}());
Tested:
---
* Chrome v12
* Node.JS v0.4.9
* Firefox v5
* MSIE 8
Why:
---
In short: it's some weird quirk. See the comments below (or the post above)
In `strict mode` `this` is never the global, but also in `strict mode` `eval` operates in a separate context in which `this` *is* always the global.
In non-strict mode `this` is the current context. If there is no current context, it assumes the global. An anonymous function has no context and hence in non-strict mode assumes the global.
Sub Rant:
There's a silly misfeature of JavaScript that 99.9% of the time just confuses people called the 'comma operator'.
var a = 0, b = 1;
a = 0, 1; // 1
(a = 0), 1; // 1
a = (0, 1); // 1
a = (42, eval); // eval
a('this'); // the global object
Value of this in a node module:
this in NodeJS global scope is the current module.exports object, not the global object. This is different from a browser where the global scope is the global window object. Consider the following code executed in Node:
console.log(this); // logs {}
module.exports.foo = 5;
console.log(this); // log { foo:5 }
First we log an empty object because there are no values in module.exports in this module. Then we put foo on the module.exports object, when we then again log this we can see that it now logs the updated module.exports object.
How can we access the global object:
We can access the global object in node using the global keyword:
console.log(global);
The global object exposes a variety of useful properties about the environment. Also this is the place where functions as setImmediate and clearTimeout are located.
While in browsers the global scope is the window object, in nodeJS the global scope of a module is the module itself, so when you define a variable in the global scope of your nodeJS module, it will be local to this module.
You can read more about it in the NodeJS documentation where it says:
global
<Object> The global namespace object.In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node.js this is different. The top-level scope is not the global scope; var something inside an Node.js module will be local to that module.
And in your code when you write:
console.log(this)in an empty js file(module) it will print an empty object{}referring to your empty module.console.log(this);inside a self invoking function,thiswill point to the global nodeJS scope object which contains all NodeJS common properties and methods such asrequire(),module,exports,console...console.log(this)with strict mode inside a self invoking function it will printundefinedas a self invoked function doesn't have a default local scope object in Strict mode.
Why
It's hard to say exactly why this feature exists, but it's useful in some situations. For example, if you're using Webpack or some other packer or ES modules, variables delcared with var will not be stored in the global object and thus will not be accessible through other files. As such, if you want a variable to be available everywhere, you need to declare it directly via the global object (globalThis.varName = value).
Global Scope vs Global Object
As I noted above, variables declared inside ES modules will not be stored in the global object. You can think of the properties on the global object as variables on a "super-global" scope, above the global scope.
While the global scope includes all variables decalerd with var, let or const outside any functions in a file, the global object may or may not include all variables decalerd with var outside any functions in a file.
What ends up in the global object, the scope of the global object and how many global objects there are depends on the environment.
I cannot read the mind of Brendan Eich, but I can take an educated guess as to why the global object exists:
First of all, the design of JavaScript is kept very simple: Records (the place where variable values get stored) and Objects are very similar. Both are basically a collection of key-value pairs. That simplifies the design (e.g. a = 1 works the same way as a.b = 1) and has the side effect that objects can easily be used as records (e.g. with the with statement).
Secondly you might also want to refer to global variables although the variable got shadowed. That can easily be achieved with having a self reference inside the global object / record (window is just a self reference).
Therefore it does make sense that var creates a variable in the global record, which, you can also refer to via window..
Actually that const and let do not create a variable on the global scope is the inconsistency, but with that modularity gets achieved.
Hi there,
I have been using Javascript for quite some years for scripting here and there, and as the need for doing deeper functionalities and out of curiosity brings me to a big in-depth review of basic concepts of the language fundamentals
Something I see difficult to wrap my head around is the Inheritance model and Prototype Chain. My main documentation sources for this matter are
mdnjs - Global objects mdnjs - Inheritance and the prototype chain mdnjs - Object
I get that the global namespace is addreaseable by globalThis
console.log(Object.getOwnPropertyDescriptors(globalThis));
In a more simplyfied way, just seeing the keys by using Object.keys(obj) would be
console.log(Object.keys(Object.getOwnPropertyDescriptors(globalThis)));
We can see all the Standard built-in Objects from here. They are all 'aliased' to the global namespace so that
console.log(globalThis.Array === Array); // True
Ok now we can access all the Global Objects to see their properties and methods by (lets say in the case of Array)
// Static methods console.log(Object.keys(Object.getOwnPropertyDescriptors(Array))); // Instance methods console.log(Object.keys(Object.getOwnPropertyDescriptors(Array.prototype))); // Prototype the constructor function console.log(Object.keys(Object.getOwnPropertyDescriptors(Object.getPrototypeOf(Array))));
We can do this also with Object, and with the rest Global Objects.
What I fail to see , is:
- 1st) The hierarchy:
- Knowing that Object is parent of all the Objects
- How can I manually demonstrate that Array an other Standard Objects are descendant of Object?
- 2nd) Why Array would list Static methods of Array , while Array.prototype are the Instance methods ?
- 3rd) What does exactly the Prototype of the Constructor function means?How could I create my own object say Popcorn, that will be direct descendant of Object ?
It is a nice trip on understanding, and hopefully I will end up figuring out, but anyone helping pave the way will be so much appreciated.
Thank you.