闭包编译器对此不应用@cconst

Closure Compiler does not apply @const on this

本文关键字:应用 @cconst 编译器 闭包      更新时间:2023-09-26

我正在尝试让这段代码正常工作:

/** @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);

我已经尝试添加更多的注释(类型、构造函数),@enum而不是@const(用于this.bar)、me = this,所有这些都没有任何效果。

帮助页面在这方面并没有真正的帮助。

有什么办法让它发挥作用吗?如果没有,为什么?

编译器没有任何通用的"内联属性"逻辑。您可以使用原型函数在ADVANCED模式下将其内联

/** @constructor */
function Foo() {}
Foo.prototype.bar = function() { return 5 };
var f = new Foo();
alert(f.bar());

将编译为:

alert(5);

如果方法"bar"只有一个定义,并且"bar"只在调用表达式中使用过,则编译器将执行此操作。在一般情况下,用于此操作的逻辑是不正确的(如果调用所在的对象没有定义调用将抛出的"bar")。然而,它被认为"足够安全"。

添加/** @constructor */作品:

/** @constructor */
function Foo()
{
    /** @const */ 
    this.bar = 5;
    // cc does not complain
    //this.bar = 3;
}
var f = new Foo();
// should be inlined
alert(f.bar);

编译为:

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

如果我取消注释this.bar = 3;,我会得到预期的警告:

JSC_CONSTANT_PROPERTY_REASSIGNED_VALUE: constant property bar assigned a value more than once at line 9 character 0
this.bar = 3;
^

在文档中说:

如果一个用@cconst标记的变量被多次赋值,编译器将产生警告。If the variable is an object, note that the compiler does not prohibit changes to the properties of the object.

p.S.:您在脚本或HTML页面中包含了以下代码吗?

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