我正在定义一个简单的对象“浏览器”,它允许显示列表中的“上一张”和“下一张”图像。
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;
};
这段代码几乎被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;
这表明我不了解 javascript oop。
我做错了什么?
最佳答案
JSC_USED_GLOBAL_THIS:全局 this 对象的危险使用。
此警告意味着您在原型(prototype)函数或构造函数之外使用了关键字 this。例如,以下代码将产生此警告:
// Produces JSC_USED_GLOBAL_THIS warning:
this.foo = 1;
在这种情况下,this 实际上指的是全局 this 对象。对于标准网页,全局对象与窗口对象是一回事。如果收到此警告,请确保您确实打算引用全局对象。
请注意,编译器仅将使用 @constructor JSDoc 注释的函数识别为构造函数,如下所示:
/**
* @constructor
*/
function MyFunction() {
this.foo = 1;
}
https://developers.google.com/closure/compiler/docs/error-ref
关于javascript - javascript 中 "this."的不当使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14778068/