手写bind,call,apply,柯里化

bind

    Function.prototype.myBind = function(context = window) {
      let obj = { ...context };
      obj.fn = this;
      return obj.fn;
    };

call

    Function.prototype.myCall = function(context = window, ...arr) {
      context.fn = this;
      let result = context.fn(...arr);
      delete context.fn;
      return result;
    };

apply

    Function.prototype.myApply = function(context = window, arr) {
      context.fn = this;
      let result = context.fn(...arr);
      delete context.fn;
      return result;
    };

柯里化实现a(1,2,3)或a(1)(2)(3)

    function currying(fn, ...arr1) {
      return function(...arr2) {
        let arr = [...arr1, ...arr2];
        if (arr.length < fn.length) {
          return currying(fn, ...arr);
        } else {
          return fn.apply(this, arr);
        }
      };
    }
    function add(x, y, z) {
      console.log(x + y + z);
      return x + y + z;
    }
    let a = currying(add);

  

posted @ 2020-05-19 17:50  把我当做一棵树叭  阅读(216)  评论(0)    收藏  举报