Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

javascript - Closure Compiler Warning `dangerous use of the global this object`?

Dear folks, Closure Compiler gives this warnings in Advanced Mode, underlining {this.

JSC_USED_GLOBAL_THIS: dangerous use of the global this object at line 200 character 33 hovers[i4].onfocus = function() {this.className += "Hovered";}

JSC_USED_GLOBAL_THIS: dangerous use of the global this object at line 201 character 32 hovers[i4].onblur = function() {this.className = this.className.replace(/Hove...

JSC_USED_GLOBAL_THIS: dangerous use of the global this object at line 201 character 49 hovers[i4].onblur = function() {this.className = this.className.replace(/Hove...

JSC_USED_GLOBAL_THIS: dangerous use of the global this object at line 218 character 38 buttons[i5].onmouseover = function() {this.className += "Hovered";}

Q1. Whats so dangerous about this?
Q2. Should I change this?
Q3. How do I improve/solve this code?

merci!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you know the type of the "this" variable, you can declare it with a JsDoc to stop the compiler from complaining:

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

Caveat: this, however, assumes you know for sure the type of the "this" variable. This may not be as easy as it seems. For example:

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

You would have known that "this" in doSomething refers to foo. However, if you use the Advanced Mode of the Closure Compiler, the compiler may "flatten" the foo namespace and you'll end up with:

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

with foo.doSomething being "flattened" to a single global variable a. In this case, the "this" variable obviously points to the global object instead! Your code will break!

Therefore, the Closure Compiler is quite adamant in warning you not to use "this" in functions that can be flattened. You may use "this" in constructors and prototype functions without this warning though.

To resolve this, it is better to avoid using "this" by using the namespace itself:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...