【问题标题】:Closure Compiler Warning `dangerous use of the global this object`?关闭编译器警告“危险使用全局 this 对象”?
【发布时间】:2013-11-20 04:02:58
【问题描述】:

亲爱的朋友们,Closure Compiler 在高级模式下会给出这个警告,下划线{this.

JSC_USED_GLOBAL_THIS:在第 200 行字符 33 处危险地使用全局 this 对象 hovers[i4].onfocus = function() {this.className += "Hovered";}

JSC_USED_GLOBAL_THIS:在第 201 行字符 32 处危险地使用全局 this 对象 hovers[i4].onblur = function() {this.className = this.className.replace(/Hove...

JSC_USED_GLOBAL_THIS:在第 201 行字符 49 处危险地使用全局 this 对象 hovers[i4].onblur = function() {this.className = this.className.replace(/Hove...

JSC_USED_GLOBAL_THIS:在第 218 行字符 38 处危险地使用全局 this 对象 buttons[i5].onmouseover = function() {this.className += "Hovered";}

第一季度。这有什么危险?
Q2。我应该改变这个吗?
Q3.如何改进/解决此代码?

谢谢!

【问题讨论】:

标签: javascript jquery debugging google-closure-compiler


【解决方案1】:

如果你知道“this”变量的类型,你可以用 JsDoc 声明它来阻止编译器报错:

hovers[i4].onfocus = 
/** @this {Element} */
function() {this.className += "Hovered";}

警告:然而,这假设您肯定知道“this”变量的类型。这可能不像看起来那么容易。例如:

foo.doSomething = function(x) { this.bar = x; }
foo.doSomething("Hello");

您会知道doSomething 中的“this”指的是foo。但是,如果您使用闭包编译器的高级模式,编译器可能会“扁平化”foo 命名空间,您最终会得到:

a = function(x) { this.b = x }
a("Hello");

foo.doSomething 被“扁平化”为单个全局变量 a。在这种情况下,“this”变量显然指向了全局对象!你的代码会坏掉的!

因此,闭包编译器非常坚决地警告您不要在可以展平的函数中使用“this”。不过,您可以在构造函数和原型函数中使用“this”而不出现此警告。

要解决这个问题,最好通过使用命名空间本身来避免使用“this”:

foo.doSomething = function(x) { foo.bar = x; }
foo.doSomething("Hello");

【讨论】:

  • 对于任何定义类的函数,您应该使用 @constructor is JSDoc 来消除此警告。这是谷歌针对此类警告推荐的一种方式
【解决方案2】:

“this”在不同的上下文中可能有不同的含义,所以它会准确地告诉你。 您可以改用闭包:

代替

hovers[i4].onfocus = function() {this.className += "Hovered";}

有:

hovers[i4].onfocus = function(self) 
{
    return function() {self.className += "Hovered";}
}(hovers[i4])

【讨论】:

  • “危险使用 this”并不是试图警告用户在不同上下文中“this”的不同含义。这是一个警告,告诉用户,如果编译器决定 flatten 命名空间,“this”的任何使用都将指向错误的对象并会破坏代码。这是一个纯粹与编译器执行的优化有关的警告。
  • @Stephen Chung:嗯,我的意思是一样的。如果您认为我说错了,请随时编辑我的答案 - 英语不是我的母语,我可能会用错词句:)
【解决方案3】:

只是添加@marcinkuzminski 对@stephen Chung 回答添加评论的示例

 /**
 * Model for ListBox
 *
 * @constructor <-- add this to remove the warning
 */
MyProject.ListBoxModel = function ( data ){

  this.data_  = data || {};   /* this gives warning */
};

来源:https://developers.google.com/closure/compiler/docs/js-for-compiler

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多