學習一種語言,自然要看看市面上的好書是一種捷徑。這幾天,我抽空看了看JavaScript Patterns和JavaScript good parts兩本書,算是知識儲備吧。
#ASI (Automatic Semicolon insert)
JavaScript把自己搞得很只能,如果程式碼末尾少了“;”,他還會擇機給你加上一個。JavaScript Interpreter又不是神,時常會犯錯誤,所以通常我們不給他ASI爽一把的機會。
// Goodif (XX) { // ....}// Bad.// Piaoger以前喜歡這種方式,看來得改改了,// 爭取寫C/C++還有JavaScritpt時代碼風格相似吧。if (XX){ // ....}//Good if( color === RED || color === BLUE) { // ....}// Badif( color === RED || color === BLUE) { // ....}
#Anonymous Functions (匿名函數)
Anonymous Functions通常出現在無需複用的函數中,可以有效控制變數範圍,構造閉包 (Closure),防止對全域變數造成汙染。
(function(){ // insert code here})();
在jquery等JavaScript庫中經常能見到。
#Module Pattern
http://www.yuiblog.com/blog/2007/06/12/module-pattern/
# 盡量把<script>放到Html內容的後面
無論是針對JavaScript檔案還是JavaScript語句,最好放到Html Body的最後部分;
For performance reasons, script blocks can also be placed at the bottom of the document body
# Delayloading