I was reading through the code segment of closure library, I saw this code fragment there:
/**
* Gets the document object being used by the dom library.
* @return {!Document} Document object.
*/
goog.dom.getDocument = function() {
return document;
};
Why we have wrapped the document reference in the getter method? isn't document is a global object?
I see two logical reasons, both involving the Closure Compiler:
Type checking - When calling this function, the Closure Compiler will know that the return type is of type Document
and that it is never null. Presumably Google Closure developers could have hard-coded this into the Closure Compiler, but by being explicit they avoid adding special cases to the Closure Compiler for properties that exist on the global object.
Minification - When that function goes through ADVANCED_OPTIMIZATIONS
, goog.dom.getDocument
can get minified to something like a.b.c
. The Closure Compiler cannot rename document
because it has no control over the variable name on the global object, but it can certainly rename functions that reference document
to give you smaller source code.