[英]“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
警告有關的警告的詳細說明:
關於使用全局this
對象的警告有助於防止在不使用new
關鍵字的情況下意外調用構造函數,這將導致構造函數屬性泄漏到全局范圍內。 但是, /** @constructor */
編譯器知道打算將哪些函數用作構造函數,必須使用注釋/** @constructor */
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.