• 柯理化函數(shù)思想:一個(gè)js預(yù)先處理的思想;利用函數(shù)執(zhí)行可以形成一個(gè)不銷(xiāo)毀的作用域的原理,把需要預(yù)先處理的內(nèi)容都儲(chǔ)存在這個(gè)不銷(xiāo)毀的作用域中,并且返回一個(gè)小函數(shù),以后我們執(zhí)行的都是小函數(shù),在小函數(shù)中把之前預(yù)先存儲(chǔ)的值進(jìn)行相關(guān)的操作處理即可;
• 柯里化函數(shù)主要起到預(yù)處理的作用;
• bind方法的作用:把傳遞進(jìn)來(lái)的callback回調(diào)方法中的this預(yù)先處理為上下文context;
/*** bind方法實(shí)現(xiàn)原理1* @param callback [Function] 回調(diào)函數(shù)* @param context [Object] 上下文* @returns {Function} 改變this指向的函數(shù)*/function bind(callback,context) {  var outerArg = Array.prototype.slice.call(arguments,2);// 表示取當(dāng)前作用域中傳的參數(shù)中除了fn,context以外后面的參數(shù);  return function (){    var innerArg = Array.prototype.slice.call(arguments,0);//表示取當(dāng)前作用域中所有的arguments參數(shù);    callback.apply(context,outerArg.concat(innerArg));  }}/*** 模仿在原型鏈上的bind實(shí)現(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);  }}以上這篇javascript中利用柯里化函數(shù)實(shí)現(xiàn)bind方法【推薦】就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注