“dangerous use of the global this object” warning in Google Closure Compiler

后端 未结 2 845
北海茫月
北海茫月 2020-12-19 21:16

I have some code that looks like this:

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

相关标签:
2条回答
  • 2020-12-19 21:39

    I would recommend writing it like this:

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

    However, the real fix is to use the @constructor JSDoc notation on the line before the constructor:

    /** @constructor */
    
    0 讨论(0)
  • 2020-12-19 21:45

    The Closure Compiler Error and Warning Reference provides detailed explanations for the warnings related to the dangerous use of this:

    • JSC_UNSAFE_THIS
    • JSC_USED_GLOBAL_THIS

    The warning about using the global this object helps prevent accidentally calling a constructor function without the new keyword, which would result in the constructor properties leaking into the global scope. However, for the compiler to know which functions are intended to be constructors, the annotation /** @constructor */ is required.

    0 讨论(0)
提交回复
热议问题