2012-04-01 58 views
3

我试图让这片代码工作的:关闭编译不适@const这个

/** @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所有这些都没有任何影响。

help page对此没有什么帮助。

有没有办法让这个工作? 如果不是,为什么?

回答

2

编译器没有任何通用的“内联属性”逻辑。您可以通过使用原型功能得到这个在高级模式下内联:

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

var f = new Foo(); 
alert(f.bar()); 

将编译为:

alert(5); 

编译器会做,如果只有一个方法“栏的单一定义“和”酒吧“只在调用表达式中使用。用于此的逻辑在一般情况下不正确(如果调用位于未定义“bar”的对象上,则该调用将抛出)。但是,它被认为“足够安全”。

+0

当前缀'@ const'注释时,变量将被内联(称为[constant propagation] //en.wikipedia.org/wiki/Constant_propagation))通过Closure编译器,这对于正常的'var'语句非常有效,这就是我想用属性重现的行为,它与你描述的过程有任何关系 – copy 2012-04-02 18:55:32

+0

正如我所说的,编译器有不支持这个。它会在类属性时检查@const注释,但在执行优化时实际使用该信息会更保守。 – John 2012-04-02 23:20:24

+0

我多花了一些时间与编译器一起玩,但认为你是对的;似乎没有办法做到这一点。无论如何,我现在正在使用cpp。 – copy 2012-04-06 17:22:26

2

添加/** @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; 
^ 
+0

它仍然不像其他常量那样内嵌'f.bar'。这应该输出'alert(5)'。 – copy 2012-04-01 04:47:45

+0

http://code.google.com/p/closure-compiler/issues/detail?id=287 :( – stewe 2012-04-01 07:57:05

+0

好吧,这听起来像是坏消息,无论如何你的帮助+1。仍然寻找一个黑客来做到这一点 – copy 2012-04-02 02:06:05

0

在文档表示:

如果标记为@const的变量多次分配一个值,则编译器会生成警告。 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> 
+0

你引用的文字表示你仍然可以改变一个常量对象的属性,但是可以将一个对象的属性标记为常量(同样参见stewe的回答),我试图让它和' new''''''''''''''''''''''''''''''我的脚本中并没有使用Closure Library Closure Compiler在没有它的情况下完美运行 – copy 2012-04-01 07:30:16