call.apply.bind实现

call实现

Function.property.myCall = function(context = window){
  if(typeof this != 'function'){
    return throw new TypeError('Error')
  }
  context.fn = this
  let args = [...arguments].slice(1)
  const result = context.fn(...arg)
  delete context.fn
  return result
}

apply实现

写实现-apply

Function.prototype.myApply = function(context = window) {
  if (typeof this !== 'function') {
    throw new TypeError('Error')
  }
  context.fn = this
  let result
  // 处理参数和 call 有区别
  if (arguments[1]) {
    result = context.fn(...arguments[1])
  } else {
    result = context.fn()
  }
  delete context.fn
  return result
}

bind实现

//mdn实现方式

if (!Function.prototype.bind) (function(){
  var slice = Array.prototype.slice;
  Function.prototype.bind = function() {
    var thatFunc = this, thatArg = arguments[0];
    var args = slice.call(arguments, 1);
    if (typeof thatFunc !== 'function') {
      // closest thing possible to the ECMAScript 5
      // internal IsCallable function
      throw new TypeError('Function.prototype.bind - ' +
             'what is trying to be bound is not callable');
    }
    return function(){
      var funcArgs = args.concat(slice.call(arguments))
      return thatFunc.apply(thatArg, funcArgs);
    };
  };
})();

new实现

function myNew(fn){
 let ret = Object.create(null)
 ret._proto_ = fn.prototype
 
 let res = fn.apply(ret, [...arguments].slice(1))

 return typeof res == "Object" ? res : ret
}

你可能感兴趣的:(call.apply.bind实现)