JS手动实现call,apply,bind

2020-05-19  本文已影响0人  无巧不成书之草色遥看

call

Function.prototype.call = function(context) {
  var context = Object(context) || window;
  context.fn = this;

  var args = [];
  for (var i = 1; i < arguments.length; i++) {
    args.push('arguments[' + i + ']');
  }
  var result = eval('context.fn(' + args + ')');
  delete context.fn;
  return result
}

apply

Function.prototype.apply = function(context, arr) {
  var context = Object(context) || window;
  context.fn = this;

  if(!arr){
    return context.fn()
  }
  var args = [];
  for (var i = 0; i < arr.length; i++) {
    args.push('arr[' + i + ']');
  }
  var result = eval('context.fn(' + args + ')');
  delete context.fn;
  return result
}

bind

Function.prototype.bind = function (context) {
  if (typeof this !== "function") {
    throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
  }
  var self = this;
  var args = Array.prototype.slice.call(arguments, 1)
  var fNOP = function () { }
  var fBound = function () {
    var bindArgs = Array.prototype.slice.call(arguments);
    return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs))
  }
  fNOP.prototype = this.prototype;
  fBound.prototype = new fNOP();
  return fBound;
}
上一篇 下一篇

猜你喜欢

热点阅读