小白手写实现call

106 阅读1分钟
/*
1.如果需要每个函数都可以像call那样被调用,
  内部实现是为所有函数都添加上call函数,
  即在函数的原型上添加call函数
*/

/* 
...anySum:是ES6语法中的拓展运算符(用来处理剩余参数)
*/


Function.prototype.ownCall = function(thisArg,...anySum){
  // console.log("ownCall被调用了");
  //利用隐式绑定,调用需要被调用的函数
  var fn = this 
  //判断传进来的参数是否为null|undefined,是的话this则指向window
  var thisArg = thisArg ? Object(thisArg):window  
   //将传进来的参数转换成数组,否则传入Number|String将会报错
  // thisArg = Object(thisArg)
   //利用隐式绑定使被调用的函数this指向这个参数
  thisArg.fn = fn
   //传入的参数第一个被thisArg匹配了,其余的会被加入到anySum这个数组中
  thisArg.fn(...anySum) 
  delete thisArg.fn
}
function foo(num1,num2){
  console.log("foo函数被调用",this);
  console.log(num1+num2);
}

// foo.call()
foo.ownCall(undefined,20,30)