JavaScript高级之手写call

65 阅读1分钟

什么是call?

官方说法: call()  方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。

我的理解:就是可以改变函数的this指向,并且还能传入参数 如下面的sum函数普通调用时,this指向是window,当call调用时,就变成了字符串call

function sum(num1,num2){
    console.log('sum 被调用',this,num1,num2)
}
// call
sum() // window
sum.call('call',10,30) // [String: 'call'] 10 30

是不是很好理解! 让我们简单实现下

Function.prototype.xycall = function(thisArg,...args){
  let fn = this
  thisArg = thisArg ? Object(thisArg) : window
  thisArg.fn = fn 
  thisArg.fn(...args)
  delete thisArg.fn
}