Ke Lihua’s function idea: An idea of js pre-processing; using the principle of function execution to form a non-destroyed scope, store all the content that needs to be pre-processed in this non-destructed scope , and returns a small function. From now on, we will execute small functions. In the small function, we can perform relevant operations on the previously stored values;
The currying function mainly plays a preprocessing role;
The role of the bind method: Preprocess this in the callback method passed in as the context context;
/** * bind方法实现原理1 * @param callback [Function] 回调函数 * @param context [Object] 上下文 * @returns {Function} 改变this指向的函数 */ function bind(callback,context) { var outerArg = Array.prototype.slice.call(arguments,2);// 表示取当前作用域中传的参数中除了fn,context以外后面的参数; return function (){ var innerArg = Array.prototype.slice.call(arguments,0);//表示取当前作用域中所有的arguments参数; callback.apply(context,outerArg.concat(innerArg)); } }
/** * 模仿在原型链上的bind实现原理(柯理化函数思想) * @param context [Object] 上下文 * @returns {Function} 改变this指向的函数 */ 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); } }
The above is the relevant code for using the currying function to implement the bind method. I hope it will be helpful to everyone in learning javascript programming.