javascript - javascript 中 "this."的不当使用

标签 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;
};

这段代码几乎被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/

相关文章:

javascript - Nativescript 和 ListView,项目未定义

javascript - 当通过 Javascript 按下回车按钮时调用一个函数

javascript - 闭包编译器 : Avoid "missing return statement" warning when a return is guaranteed

javascript - 使用 Closure Compiler,Array<T> 注释与仅 Array 相比有什么好处?

javascript - 尝试进行 AJAX API 调用

javascript - 如何选择动态添加的下拉列表的默认选项

oop - UML:当一个类具有指向另一类的方法参数指针时

C++ 继承 : Do I have to repeat parent attributes in derived classes?

c++ - 在类中初始化 vector

java - 闭包编译器选项