Cosen95 / fe_interview

字节、阿里、美团、滴滴、腾讯等大厂高级前端面试题整理
238 stars 25 forks source link

手写apply() #87

Open Cosen95 opened 4 years ago

Cosen95 commented 4 years ago
Function.prototype.apply2 = function (context, arr) {
  var context = context || window;
  context.fn = this;
  var result;
  if (!arr) {
    result = context.fn();
  } else {
    var args = [];
    for (var i = 0, len = arr.length; i < len; i++) {
      args.push("arr[" + i + "]");
    }
    result = eval("context.fn(" + args + ")");
  }
  delete context.fn;
  return result;
};

var value = 1;
var obj = {
  value: 2,
};

function bar(name, age) {
  // console.log("value", this);

  return {
    value: this.value,
    name: name,
    age: age,
  };
}

console.log(bar.apply2(null));

// console.log(bar.apply2(obj, ["kevin", 25]));