fe_interview icon indicating copy to clipboard operation
fe_interview copied to clipboard

手写call()

Open Cosen95 opened this issue 6 years ago • 1 comments

Cosen95 avatar Apr 07 '20 08:04 Cosen95

Function.prototype.call2 = function (context) {
  var context = context || window;
  context.fn = this;
  var args = [];
  for (var i = 1, len = arguments.length; i < len; i++) {
    args.push("arguments[" + i + "]");
  }

  var result = eval("context.fn(" + args + ")");

  delete context.fn;
  return result;
};

var value = 2;

var obj = {
  value: 1,
};

function bar(name, age) {
  console.log(this.value, window);
  return {
    value: this.value,
    name: name,
    age: age,
  };
}

bar.call(null); // 2

console.log(bar.call2(obj, "kevin", 18));

Cosen95 avatar Sep 10 '20 09:09 Cosen95