2013-11-20 24 views
-1

我準備三個文件:爲什麼閉包編譯不使用externs(var x = {}並且需要window.x = {})?

java -jar compiler.jar --js=utf8.js --js_output_file=utf8-advanced.js --charset=utf8 --compilation_level=ADVANCED_OPTIMIZATIONS --formatting=SINGLE_QUOTES --formatting=PRETTY_PRINT --externs=externs.js --use_only_custom_externs 

的Javascript:

window.erest['module'] = window.erest['module'] || {}; 
window.erest.module = window.erest['module']; 

var module = window.erest.module; 

window.erest.module.hello = function() { 
    for (var i = 0; i < 5; i++) { 
     window.erest.debug.hello(); 
    } 
} 

window.erest.module.max = function() { 
    var list = []; 
    for (var i = 0; i < list.length; i++) { 
     window.erest.debug.hello(); 
    } 
} 

window.erest.module.maximum = function() { 
    window.erest.debug.hello(); 
} 

實習醫生:

/** 
* @externs 
*/ 

/** 
* @noalias 
*/ 
var erest = {}; 

erest.debug = {}; 

/** 
* @return null 
*/ 
erest.debug.hello = function() {}; 

輸出:

window.a.module = window.a.module || {}; 
window.a.b = window.a.module; 
window.a.b.hello = function() { 
    for (var b = 0;5 > b;b++) { 
    window.a.debug.hello(); 
    } 
}; 
window.a.b.max = function() { 
    for (var b = [], c = 0;c < b.length;c++) { 
    window.a.debug.hello(); 
    } 
}; 
window.a.b.c = function() { 
    window.a.debug.hello(); 
}; 

問題 - 爲什麼不實習醫生作品在這裏:

window.a.debug.hello() should be window.erest.debug.hello() 

爲什麼這樣的extern忍不住道:

var erest = {}; 

回答

1

封閉,編譯器看到全局對象不是全局變量,不同對象的屬性。您必須始終引用一個名稱。

Understanding the Restrictions Imposed by the Closure Compiler

+0

下的「參考變量作爲全局對象的屬性」子彈我發現,先進的優化都不是爲我好 - 因此它需要更多的測試/ $更作弄,並容易使錯誤。簡單的優化足以使閱讀代碼變得複雜一些,並減少了大小。 – Chameleon

相關問題