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()方法啓發,當中應用了柯里化,這種方式確實剛開始很差理解,觀看了張鑫旭的博客後,纔對柯里化的方式有了一點了解。app
軟綁定代碼,以下:優化
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。this