欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

返回函數(shù)的JavaScript函數(shù)

 更新時間:2016年06月14日 14:57:40   投稿:lijiao  
理解返回函數(shù)的JavaScript函數(shù)是什么意思,通過幾個簡短的例子真正理解返回函數(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í)行過程。

這是一種非常有用的技術,能幫你消除重復相似的代碼,如果使用的恰當,能讓你的代碼更可讀,更易維護!

大家理解了嗎?

相關文章

最新評論