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

后端 未结 3 1422
北荒
北荒 2020-12-05 19:39

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

JSC_USED_GLOBAL_THIS: dangerous use of the global this object at l

相关标签:
3条回答
  • 2020-12-05 19:45

    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");
    
    0 讨论(0)
  • 2020-12-05 19:56

    Just to add example of what @marcinkuzminski added comment to @stephen Chung answer

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

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

    0 讨论(0)
  • 2020-12-05 19:57

    "this" might have different meaning in different context, so it tells you exactly that. You can use closures instead:

    Instead of

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

    have:

    hovers[i4].onfocus = function(self) 
    {
        return function() {self.className += "Hovered";}
    }(hovers[i4])
    
    0 讨论(0)
提交回复
热议问题