var currying = function(fn){ var Args = [].slice.call(arguments, 1); //此时Args = ['aaa']; return function(/*get调用时传入的参数*/){ //此时arguments = ['bbb','ccc','ddd','eee']; newArgs = ['aaa','bbb','ccc','ddd','eee']; var newArgs = Args.concat([].slice.call(arguments)); return fn.apply(null, newArgs); } }; var get = currying(function(){ //这里的allArgs = newArgs; var allArgs = [].slice.call(arguments); console.log(allArgs.join(';')); }, 'aaa'); get('bbb','ccc','ddd','eee') //[aaa;bbb;ccc;ddd;eee]
主要是受到《你不知道的JavaScript(上卷)》中,软绑定softBind()方法启发,当中应用了柯里化,这种方式确实刚开始不好理解,观看了张鑫旭的博客后,才对柯里化的方式有了一点了解。
软绑定代码,如下:
if( !Function.prototype.softBind ){ Function.prototype.softBind = function(obj){ var fn = this; var curried = [].slice.call(arguments, 1); var bound = function(){ return fn.apply( ( !this || this ===(window || global) ) ? obj : this, curried.concat.apply( curried , arguments ) ); }; bound.prototype = Object.create( fn.prototype ); return bound; }; }
软绑定优化了硬绑定,使this指向更加灵活,可以使用隐式绑定或者显式绑定修改this。