Home >Web Front-end >JS Tutorial >Using currying function to implement bind method in javascript

Using currying function to implement bind method in javascript

PHPz
PHPzOriginal
2016-05-16 15:02:561225browse

The following editor will bring you an article using currying function to implement the bind method in javascript. The editor thinks it’s pretty good, so I’d like to share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

• Ke Lihua’s function idea: a js pre-processing idea; using the principle of function execution to form a non-destructible scope, all content that needs to be pre-processed is stored in this non-destructible 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 Function;

• The function of bind method: pre-process this in the callback method passed in as 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 entire content of using the currying function to implement the bind method in JavaScript. I hope it can give you a reference.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn