美文网首页
JS手动实现call,apply,bind

JS手动实现call,apply,bind

作者: 无巧不成书之草色遥看 | 来源:发表于2020-05-19 14:46 被阅读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;
}

相关文章

网友评论

      本文标题:JS手动实现call,apply,bind

      本文链接:https://www.haomeiwen.com/subject/hcdbohtx.html