2012-04-01 35 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