简体   繁体   中英

Closure Compiler does not apply @const on this

I am trying to get this piece of code working:

/** @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 have already tried adding more annotations (types, constructor), @enum instead of @const (for this.bar ), me = this all of which did not have any effect.

The help page was not really helpful on this.

Is there some way to get this working ? If not, why ?

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

compiles to:

alert((new function() { this.a = 5 }).a);

if i uncomment the 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;
^

The compiler doesn't have any general "inline properties" logic. You can get this to inline in ADVANCED mode by using a 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 there is only a single definition of a method "bar" and "bar" is only ever used in a call expression. The logic used for this isn't correct in the general case (if the call is on a object that doesn't define "bar" the call would throw). It is, however, considered "safe enough".

In the documentation is said that:

The compiler produces 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: did you include the following code in your script or HTML Page ?

  <script src="closure-library/closure/goog/base.js"></script>

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