手写bind

79 阅读1分钟

1、不考虑兼容

Function.prototype.bind = function (context, ...args) {
    return (...params) => {
        let result = this.apply(context, args.concat(params))
        return result
    }
}

2、考虑兼容

 Function.prototype.bind = function bind(context) {
  if (context == null) context = window;
  var params = [].slice.call(arguments, 1),
      self = this;
  return function proxy() {
      var args = [].slice.call(arguments);
      params = params.concat(args);
      return self.apply(context, params);
    };
 };

3、事件绑定

   document.onclick = fn.bind(obj, 10, 20);
    // + document.onclick = proxy