[英]“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.