Function.prototype.call = function(context) {
// 判断传入的context是不是null或者undefined,如果是的话,将context设置为全局对象
if(!context) {
context = typeof window === 'undefined' ? global : window;
}
context.fn = this// this是指向当前函数
let res = [...arguments].slice(1)
let result = context.fn(...res) // 隐式绑定 执行函数
console.log(result)
delete context.fn
return result
}
call的使用,主要有两个结果
- call 改变了 this 的指向,指向到 foo
- bar 函数执行了
手写的过程 可以通过这种方式进行理解
- 判断传入的内容
- 将函数设为对象的属性
- 接收参数
- 执行该函数
- 删除该函数