【问题标题】:"dangerous use of the global this object" warning in Google Closure CompilerGoogle Closure Compiler 中的“危险使用全局 this 对象”警告
【发布时间】:2012-07-01 10:10:32
【问题描述】:

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

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

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

感谢您的建议。

【问题讨论】:

标签: javascript google-closure-compiler


【解决方案1】:

我会推荐这样写:

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

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

/** @constructor */

【讨论】:

  • 好的,谢谢,是缺少@constructor 导致了问题。
  • 如果这是一个修改现有对象的函数(而不是用“new”调用的方法),您可以使用“@this {SomeType}”注解。
【解决方案2】:

Closure Compiler Error and Warning Reference 提供了与危险使用this 相关的警告的详细解释:

  • JSC_UNSAFE_THIS
  • JSC_USED_GLOBAL_THIS

关于使用全局this 对象的警告有助于防止意外调用没有new 关键字的构造函数,这会导致构造函数属性泄漏到全局范围内。然而,为了让编译器知道哪些函数打算作为构造函数,需要注解/** @constructor */

【讨论】:

    猜你喜欢
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    相关资源
    最近更新 更多