编程实践-使用helper方法隐藏对象

Programming practices - using helper method to hide object

本文关键字:方法 隐藏 对象 helper 使用 编程      更新时间:2023-09-26

我正在阅读闭包库的代码段,我在那里看到了这个代码片段:

/**
 * Gets the document object being used by the dom library.
 * @return {!Document} Document object.
 */
goog.dom.getDocument = function() {
  return document;
};

为什么我们将文档引用封装在getter方法中?文档不是全局对象吗?

我看到了两个逻辑原因,都涉及闭包编译器:

  1. 类型检查-调用此函数时,闭包编译器将知道返回类型为Document类型,并且它从不为null。据推测,Google Closure开发人员可能已经将其硬编码到了Closure编译器中,但通过显式,他们避免了为全局对象上存在的属性向Closure Compiler添加特殊情况。

  2. 缩小-当该函数通过ADVANCED_OPTIMIZATIONS时,goog.dom.getDocument可以缩小为类似a.b.c的大小。闭包编译器无法重命名document,因为它无法控制全局对象上的变量名,但它当然可以重命名引用document的函数,以提供更小的源代码。