幾個星期前,我發了一條微博說我喜歡返回函數的函數。很快就出現了幾個回復,基本是都是….什么東東?!對于一個程序員來說,理解返回函數的函數是一個非常重要的技能,使用它你能節省很多代碼,讓JavaScript更高效,讓你進一步理解JavaScript的強大之處。下面是我寫的幾個簡單的例子,我希望通過它你能理解我所表達的意思。
假設你有一個對象,包含有兩個子對象,它們都有get方法,這兩個方法非常相似,稍有不同:
var accessors = { sortable: { get: function() { return typeof this.getAttribute('sortable') != 'undefined'; } }, droppable: { get: function() { return typeof this.getAttribute('droppable') != 'undefined'; } }};重復的代碼不是一個好的現象,所以我們要創建一個外部函數,接受一個屬性名稱:
function getAttribute(attr) { return typeof this.getAttribute(attr) != 'undefined';}var accessors = { sortable: { get: function() { return getAttribute('sortable'); } }, droppable: { get: function() { return getAttribute('droppable'); } }};這樣好多了,但仍不完美,因為還是有些多余的部分,更好的方法是要讓它直接返回最終需要的函數――這樣能消除多余的函數執行:
function generateGetMethod(attr) { return function() { return typeof this.getAttribute(attr) != 'undefined'; };}var accessors = { sortable: { get: generateGetMethod('sortable') }, droppable: { get: generateGetMethod('droppable') }};/* 它跟最初的方法是完全等效的:*/var accessors = { sortable: { get: function() { return typeof this.getAttribute('sortable') != 'undefined'; } }, droppable: { get: function() { return typeof this.getAttribute('droppable') != 'undefined'; } }};*/上面你看到的就是一個返回函數的函數;每個子對象里都有了自己的get方法,但卻去掉了多余的函數嵌套執行過程。
這是一種非常有用的技術,能幫你消除重復相似的代碼,如果使用的恰當,能讓你的代碼更可讀,更易維護!
大家理解了嗎?
新聞熱點
疑難解答