返回函数的JavaScript函数


几个星期前,我发了一条微博说我喜欢返回函数的函数。很快就出现了几个回复,基本是都是….什么东东?!对于一个程序员来说,理解返回函数的函数是一个非常重要的技能,使用它你能节省很多代码,让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方法,但却去掉了多余的函数嵌套执行过程。

这是一种非常有用的技术,能帮你消除重复相似的代码,如果使用的恰当,能让你的代码更可读,更易维护!

大家理解了吗?


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3