手写call+apply+bind

39 阅读1分钟

手写call

Function.prototype._call = function (cs, ...args) {
  const o = (cs === undefined) ? window : Object(cs);
  const key = Symbol();
  o[key] = this;
  const result = o[key](...args);
  delete o[key];
  return result;
};
};

手写apply

Function.prototype._apply = function (cs, array = []) {
  const o = (cs === undefined) ? window : Object(cs);
  const key = Symbol();
  o[key] = this;
  const result = o[key](...array);
  delete o[key];
  return result;

手写bind

Function.prototype._bind = function(ctx, ...args) {
  // 下面的this就是调用_bind的函数,保存给_self
  const _self = this
  // bind 要返回一个函数, 就不会立即执行了
  const newFn = function(...rest) {
    // 调用 call 修改 this 指向
    return _self.call(ctx, ...args, ...rest)
  }
  if (_self.prototype) {
    // 复制源函数的prototype给newFn 一些情况下函数没有prototype,比如箭头函数
    newFn.prototype = Object.create(_self.prototype);
  }
  return newFn
}