返回函數(shù)的JavaScript函數(shù)
幾個星期前,我發(fā)了一條微博說我喜歡返回函數(shù)的函數(shù)。很快就出現(xiàn)了幾個回復,基本是都是….什么東東?!對于一個程序員來說,理解返回函數(shù)的函數(shù)是一個非常重要的技能,使用它你能節(jié)省很多代碼,讓JavaScript更高效,讓你進一步理解JavaScript的強大之處。下面是我寫的幾個簡單的例子,我希望通過它你能理解我所表達的意思。
假設你有一個對象,包含有兩個子對象,它們都有get方法,這兩個方法非常相似,稍有不同:
var accessors = { sortable: { get: function() { return typeof this.getAttribute('sortable') != 'undefined'; } }, droppable: { get: function() { return typeof this.getAttribute('droppable') != 'undefined'; } } };
重復的代碼不是一個好的現(xiàn)象,所以我們要創(chuàng)建一個外部函數(shù),接受一個屬性名稱:
function getAttribute(attr) { return typeof this.getAttribute(attr) != 'undefined'; } var accessors = { sortable: { get: function() { return getAttribute('sortable'); } }, droppable: { get: function() { return getAttribute('droppable'); } } };
這樣好多了,但仍不完美,因為還是有些多余的部分,更好的方法是要讓它直接返回最終需要的函數(shù)——這樣能消除多余的函數(shù)執(zhí)行:
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'; } } }; */
上面你看到的就是一個返回函數(shù)的函數(shù);每個子對象里都有了自己的get方法,但卻去掉了多余的函數(shù)嵌套執(zhí)行過程。
這是一種非常有用的技術,能幫你消除重復相似的代碼,如果使用的恰當,能讓你的代碼更可讀,更易維護!
大家理解了嗎?
- js 字符串操作函數(shù)
- javascript currying返回函數(shù)的函數(shù)
- javascript 手機號碼正則表達式驗證函數(shù)
- Javascript Math ceil()、floor()、round()三個函數(shù)的區(qū)別
- js 格式化時間日期函數(shù)小結
- js function定義函數(shù)使用心得
- js 小數(shù)取整的函數(shù)
- js正則函數(shù)match、exec、test、search、replace、split使用介紹集合
- js中字符替換函數(shù)String.replace()使用技巧
- 深入解析函數(shù)指針與返回函數(shù)的指針
相關文章
產(chǎn)制造追溯系統(tǒng)之通過微信小程序?qū)崿F(xiàn)移動端報表平臺
這篇文章主要介紹了產(chǎn)制造追溯系統(tǒng)-通過微信小程序?qū)崿F(xiàn)移動端報表平臺 ,本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06javascript 獲取所有id中包含某關鍵字的控件的實現(xiàn)代碼
獲取某容器控件中id包含某字符串的控件id列表2010-11-11