louzhedong/blog

call和apply实现

louzhedong opened this issue · 0 comments

call() 方法使用一个指定的this值和若干个指定的参数来调用某个函数和方法

call调用例子


var apple = {
  size: 3
}

function eat() {
  console.log(this.size);
}

eat.call(apple); // 3

实现

Function.prototype.call2 = function (ctx) {
  var ctx = ctx || window;
  var args = [];
  for (var i = 1; i < arguments.length; i++) {
    args.push('arguments[' + i + ']');
  }
  ctx.fn = this;  // this为调用call的函数
  var result = eval('ctx.fn(' + args + ')');
  delete ctx.fn;
  return result;
}

apply 实现

Function.prototype.apply2 = function (ctx, array) {
  var ctx = ctx || window;
  ctx.fn = this;
  var result;
  if (!array) {
    result = ctx.fn();
  } else {
    var args = [];
    for (var i = 0; i < array.length; i++) {
      args.push('array[' + i + ']');
    }
    result = eval('ctx.fn(' + args + ')');
  }
  delete ctx.fn;
  return result
}