前言git
一樣一個功能,能夠用不少方法來實現,有時候因爲項目時間緊張,致使不少時候只是實現了功能,每每忽視了代碼質量。下面幾種代碼重構方法,以便你們能夠寫出更優雅的代碼。github
一,提煉函數ajax
var getUserInfo = function(){ ajax( 'http:// xxx.com/userInfo', function( data ){ console.log( 'userId: ' + data.userId ); console.log( 'userName: ' + data.userName ); console.log( 'nickName: ' + data.nickName ); }) }) // 重構後 var getUserInfo = function(){ ajax( 'http:// xxx.com/userInfo', function( data ){ printDetails( data ); }); }; var printDetails = function( data ){ console.log( 'userId: ' + data.userId ); console.log( 'userName: ' + data.userName ); console.log( 'nickName: ' + data.nickName ); };
二,合併重複的條件片斷函數
var paging = function( currPage ){ if ( currPage <= 0 ){ currPage = 0; jump( currPage ); }else if ( currPage >= totalPage ){ currPage = totalPage; jump( currPage ); }else{ jump( currPage ); } } // 重構後,把重複函數獨立出來 var paging = function( currPage ){ if ( currPage <= 0 ){ currPage = 0; }else if ( currPage >= totalPage ){ currPage = totalPage; } jump( currPage ); };
三,把條件分支語句提煉成函數spa
var getPrice = function( price ){ var date = new Date(); if ( date.getMonth() >= 6 && date.getMonth() <= 9 ){ return price * 0.8; } return price; }; // 重構後,改爲可以理解的函數 var isSummer = function(){ var date = new Date(); return date.getMonth() >= 6 && date.getMonth() <= 9; }; var getPrice = function( price ){ if ( isSummer() ){ return price * 0.8; } return price; };
四,合理使用循環
五,提早讓函數退出代替嵌套條件分支code
點擊更多blog