簡體   English   中英

Google Closure Compiler中的“危險使用全局此對象”警告

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

我有一些看起來像這樣的代碼:

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

然后我以后有這個:

var SomeObject = new MyObject();

當我通過在高級模式下關閉編譯運行我的代碼,我收到了警告dangerous use of the global this object每行,其中我有this.Prop =

我在做什么“很危險”,我應該如何重寫我的代碼?

感謝您的建議。

建議這樣寫:

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

但是,真正的解決方法是在構造函數之前的行上使用@constructor JSDoc表示法:

/** @constructor */

Closure Compiler錯誤和警告參考》提供了與危險使用this警告有關的警告的詳細說明:

  • JSC_UNSAFE_THIS
  • JSC_USED_GLOBAL_THIS

關於使用全局this對象的警告有助於防止在不使用new關鍵字的情況下意外調用構造函數,這將導致構造函數屬性泄漏到全局范圍內。 但是, /** @constructor */編譯器知道打算將哪些函數用作構造函數,必須使用注釋/** @constructor */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM