Tot*_*oto 1 javascript oop google-closure-compiler
我正在定义一个简单的对象"浏览器",它允许从列表中显示"上一个"和"下一个"图像.
function Browser(image, elements) {
this.current = 0;
this.image = image;
this.elements = elements;
}
Browser.prototype.next = function () {
if (++this.current >= this.elements.length) {
this.current = 0;
}
return this.show(this.current);
};
Browser.prototype.prev = function () {
if (--this.current < 0) {
this.current = this.elements.length - 1;
}
return this.show(this.current);
};
Browser.prototype.show = function (current) {
this.image.src = this.elements[current];
return false;
};
Run Code Online (Sandbox Code Playgroud)
这个代码几乎被JSlint所喜欢.但是"高级优化"中的Google Closure Compiler无法编译它.
它说:
JSC_USED_GLOBAL_THIS: dangerous use of the global this object at line 3 character 0
this.current = 0;
JSC_USED_GLOBAL_THIS: dangerous use of the global this object at line 4 character 0
this.image = image;
JSC_USED_GLOBAL_THIS: dangerous use of the global this object at line 5 character 0
this.elements = elements;
Run Code Online (Sandbox Code Playgroud)
这告诉我,我不懂javascript oop.
我究竟做错了什么?
JSC_USED_GLOBAL_THIS:危险使用全局此对象.
此警告意味着您在原型函数或构造函数之外使用关键字this.例如,以下代码将生成此警告:
// Produces JSC_USED_GLOBAL_THIS warning:
this.foo = 1;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,这实际上是指全局此对象.对于标准网页,全局对象与窗口对象相同.如果收到此警告,请确保您确实要引用全局对象.
请注意,如果使用@constructor JSDoc注释注释,编译器仅将函数识别为构造函数,如下所示:
/**
* @constructor
*/
function MyFunction() {
this.foo = 1;
}
Run Code Online (Sandbox Code Playgroud)
https://developers.google.com/closure/compiler/docs/error-ref