Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ignore compiler warning from one file in Google Closure

I'm using an external library (Phonegap) in a fairly large Closure project. Unfortunately Phonegap generates a ton was compiler warnings (all "dangerous use of this"). Enough that it makes searching through the compiler output for warning about my own code pretty annoying.

Is there a way to silence just the warnings from one file?

like image 632
defrex Avatar asked Mar 25 '11 15:03

defrex


1 Answers

I suppose you mean type warnings when you are using VERBOSE or checkTypes.

Put the following into any file:

/**
 * @fileoverview
 * @suppress {checkTypes}
 */

to turn off type checking for that file only. You can @suppress many other things as well. Read the Closure Compiler docs for more details.

Dangerous use of "this"

However, if you are talking about "dangerous use of this" warnings, DO NOT ignore them. They refer to places where:

  1. You have a namespace
  2. You defined a function within that namespace
  3. You use "this" inside that function -- and this can refer to the namespace
  4. That namespace may be flattened by the compiler

For example:

foo.bar.hello = "Hello World!";
foo.bar.baz = function() {
   alert(this.hello);
};
foo.bar.baz();    // this --> foo.bar

The "alert" statment will be flagged by a compiler warning of "dangerous use of this". Why? Remember, if the compiler flattens the "foo.bar" namespace:

$foo$bar$hello$ = "Hello World!";
$foo$bar$baz$ = function() { alert(this.$hello$); }
$foo$bar$baz$();   // this --> window

Notice I am using debug variables renaming here. In reality, "$foo$bar$baz" may be renamed just to "a".

You can see immediately that the call to foo.bar.baz() will fail because "this" no longer refers to "foo.bar", but refers to the global object. You code will crash with a loud CRANK!

Exception cases when "this" is OK

Now, there are cases where usage of "this" is OK. For example, in event handlers. "this" will automatically point to the DOM node that raised that event.

In these cases, you need to use the following type of JsDoc directive:

/** @this {Node} */

to specify the type expected for "this" in order to shut the compiler up.

like image 129
Stephen Chung Avatar answered Sep 30 '22 23:09

Stephen Chung