柯理化函數(shù)思想:一個js預先處理的思想;利用函數(shù)執(zhí)行可以形成一個不銷毀的作用域的原理,把需要預先處理的內容都儲存在這個不銷毀的作用域中,并且返回一個小函數(shù),以后我們執(zhí)行的都是小函數(shù),在小函數(shù)中把之前預先存儲的值進行相關的操作處理即可;
柯里化函數(shù)主要起到預處理的作用;
bind方法的作用:把傳遞進來的callback回調方法中的this預先處理為上下文context;
/*** bind方法實現(xiàn)原理1* @param callback [Function] 回調函數(shù)* @param context [Object] 上下文* @returns {Function} 改變this指向的函數(shù)*/function bind(callback,context) { var outerArg = Array.prototype.slice.call(arguments,2);// 表示取當前作用域中傳的參數(shù)中除了fn,context以外后面的參數(shù); return function (){ var innerArg = Array.prototype.slice.call(arguments,0);//表示取當前作用域中所有的arguments參數(shù); callback.apply(context,outerArg.concat(innerArg)); }} /*** 模仿在原型鏈上的bind實現(xiàn)原理(柯理化函數(shù)思想)* @param context [Object] 上下文* @returns {Function} 改變this指向的函數(shù)*/Function.prototype.mybind = function mybind (context) { var _this = this; var outArg = Array.prototype.slice.call(arguments,1); // 兼容情況下 if('bind' in Function.prototype) { return this.bind.apply(this,[context].concat(outArg)); } // 不兼容情況下 return function () { var inArg = Array.prototype.slice.call(arguments,0); inArg.length === 0?inArg[inArg.length]=window.event:null; var arg = outArg.concat(inArg); _this.apply(context,arg); }} 以上就是利用柯里化函數(shù)實現(xiàn)bind方法的相關代碼,希望對大家學習javascript程序設計有所幫助。



















