Closure compiler doesn't apply @const to this
I am trying to get this piece of code to work:
/** @constructor */
function Foo()
{
/** @const */
this.bar = 5;
// edit: does now work
// this.bar = 3;
}
var f = new Foo();
// should be inlined (like other constants)
alert(f.bar);
I've already tried adding additional annotations (types, constructor) @enum
instead of @const
(for this.bar
) me = this
, all of which had no effect.
Help page didn't help.
Is there a way to make this work? If not, why not?
source to share
There is no generic "inline properties" logic in the compiler. You can do this inline in ADVANCED mode using the prototype function:
/** @constructor */
function Foo() {}
Foo.prototype.bar = function() { return 5 };
var f = new Foo();
alert(f.bar());
will compile to:
alert(5);
The compiler will do this if only one method definition "bar" and "bar" is used only in the call expression. The logic used for this is incorrect in general (if the call is on an object that does not define a "bar" that will trigger the call). It is, however, considered "reasonably safe".
source to share
Adding /** @constructor */
works:
/** @constructor */
function Foo()
{
/** @const */
this.bar = 5;
// cc does not complain
//this.bar = 3;
}
var f = new Foo();
// should be inlined
alert(f.bar);
will compile:
alert((new function() { this.a = 5 }).a);
If I uncomment this.bar = 3;
, I get this expected warning:
JSC_CONSTANT_PROPERTY_REASSIGNED_VALUE: constant property bar assigned a value more than once at line 9 character 0
this.bar = 3;
^
source to share
The documentation says that:
The compiler issues a warning if a variable marked with @const is assigned a value more than once. If the variable is an object, note that the compiler does not prohibit changes to the properties of the object.
PS: have you added the following code to your script or HTML page?
<script src="closure-library/closure/goog/base.js"></script>
source to share