Google 闭包编译器中的“全局此对象的危险使用”警告

"dangerous use of the global this object" warning in Google Closure Compiler

本文关键字:危险 警告 对象 全局 编译器 闭包 Google      更新时间:2023-09-26

我有一些代码看起来像这样:

var MyObject = function () {
  this.Prop1 = "";
  this.Prop2 = [];
  this.Prop3 = {};
  this.Prop4 = 0;
}

然后我后来有了这个:

var SomeObject = new MyObject();

当我在高级模式下通过闭包编译器运行代码时,我在我有this.Prop =的每一行上都会收到警告dangerous use of the global this object

正在做什么是"危险"的,我应该如何重写我的代码?

感谢您的建议。

建议这样写:

function MyObject() {
  this.Prop1 = "";
  this.Prop2 = [];
  this.Prop3 = {};
  this.Prop4 = 0;
}

但是,真正的解决方法是在构造函数之前的行上使用@constructor JSDoc 表示法:

/** @constructor */

闭包编译器错误和警告参考提供了与危险使用this相关的警告的详细说明:

  • JSC_UNSAFE_THIS
  • JSC_USED_GLOBAL_THIS

有关使用全局 this 对象的警告有助于防止意外调用没有 new 关键字的构造函数,这将导致构造函数属性泄漏到全局范围内。但是,为了使编译器知道哪些函数旨在成为构造函数,需要注释/** @constructor */