[英]“dangerous use of the global this object” warning in Google Closure Compiler
[英]Closure Compiler Warning `dangerous use of the global this object`?
親愛的朋友們,Closure Compiler在高級模式中給出了這個警告,強調{this.
JSC_USED_GLOBAL_THIS:危險使用全局此對象的第200行字符33 hovers[i4].onfocus = function() {this.className += "Hovered";}
JSC_USED_GLOBAL_THIS:危險使用全局此對象的第201行字符32 hovers[i4].onblur = function() {this.className = this.className.replace(/Hove...
JSC_USED_GLOBAL_THIS:危險使用全局此對象的第201行字符49 hovers[i4].onblur = function() {this.className = this.className.replace(/Hove...
JSC_USED_GLOBAL_THIS:危險使用全局此對象的第218行字符38 buttons[i5].onmouseover = function() {this.className += "Hovered";}
Q1。 這有什么危險嗎?
Q2。 我應該改變嗎?
Q3。 如何改進/解決此代碼?
MERCI!
如果您知道“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
。 但是,如果您使用Closure Compiler的高級模式 ,編譯器可能會“展平” foo
命名空間,您將最終得到:
a = function(x) { this.b = x }
a("Hello");
與foo.doSomething
被“扁平化”為一個全局變量a
。 在這種情況下,“this”變量顯然指向全局對象 ! 你的代碼會破裂!
因此,Closure Compiler非常堅定地警告你不要在可以展平的函數中使用“this”。 您可以在構造函數和原型函數中使用“this”,但不會出現此警告。
要解決此問題,最好避免使用命名空間本身來使用“this”:
foo.doSomething = function(x) { foo.bar = x; }
foo.doSomething("Hello");
“this”在不同的上下文中可能有不同的含義,因此它會准確地告訴您。 您可以使用閉包:
代替
hovers[i4].onfocus = function() {this.className += "Hovered";}
有:
hovers[i4].onfocus = function(self)
{
return function() {self.className += "Hovered";}
}(hovers[i4])
只是添加@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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.