柯里化函数是把原来接受多个参数的函数变换成接受一个单一参数的函数,并且返回接受余下的参数而且返回结果的新函数。
function currying(fn) { var slice = Array.prototype.slice, __args = slice.call(arguments, 1); return function () { var __inargs = slice.call(arguments); return fn.apply(null, __args.concat(__inargs)); }; } function Ajax() { this.xhr = new XMLHttpRequest(); } Ajax.prototype.open = function(type, url, data, callback) { this.onload = function() { callback(this.xhr.responseText, this.xhr.status, this.xhr); } this.xhr.open(type, url, data.async); this.xhr.send(data.paras); } 'get post'.split(' ').forEach(function(mt) { Ajax.prototype[mt] = currying(Ajax.prototype.open, mt); }); var xhr = new Ajax(); xhr.get('/articles/list.php', {}, function(datas) { // done(datas) }); var xhr1 = new Ajax(); xhr1.post('/articles/add.php', {}, function(datas) { // done(datas) });