简体   繁体   中英

Improper use of “this.” in javascript

I am defining a simple object "Browser" which is allowing to display "previous" and "next" image from a list.

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

This code is almost liked by JSlint. But the Google Closure Compiler in "advanced optimization" does not compile it.

It says:

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;

Which tells me that I do not understand javascript oop.

What am I doing wrong?

JSC_USED_GLOBAL_THIS: dangerous use of the global this object.

This warning means that you use the keyword this outside of prototype function or a constructor function. For example, the following code will produce this warning:

// Produces JSC_USED_GLOBAL_THIS warning:
this.foo = 1;

In this case this actually refers to the global this object. For a standard web page, the global object is the same thing as the window object. If you get this warning, make sure that you really intended to refer to the global object.

Note that the compiler only recognizes a function as a constructor if it is annotated with the @constructor JSDoc annotation, like this:

/**
 * @constructor
 */
function MyFunction() {
  this.foo = 1;
}

https://developers.google.com/closure/compiler/docs/error-ref

From the docs :

Note that the compiler only recognizes a function as a constructor if it is annotated with the @constructor JSDoc annotation, like this:

/**
 * @constructor
 */
function MyFunction() {
  this.foo = 1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM