返回函数的JavaScript函数

来源:互联网 发布:客户地图软件 编辑:程序博客网 时间:2024/06/10 21:50

转自:http://www.webhek.com/return-javascript-functions


假设你有一个对象,包含有两个子对象,它们都有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方法,但却去掉了多余的函数嵌套执行过程。

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



0 0
原创粉丝点击