Function.prototype.call 实现原理

2,375 阅读1分钟

Function.prototype.call

方法说明

call() 允许为不同的对象分配和调用属于一个对象的函数/方法。 call() 提供新的 this 值给当前调用的函数/方法。你可以使用 call 来实现继承:写一个方法,然后让另外一个新的对象来继承它(而不是在新对象中再写一次这个方法)

源码的关键点在于

在传递进来的上下文对象中构造一个需要执行的方法,比如: ctx = { fn: test () { console.log(this.name) } },这样方法内this就会指向ctx对象,就达到了在指定的上下文对象上运行不属于它的方法

源码

Function.prototype.myCall = function (ctx, ...args) {
  // 非严格模式下,ctx为null、undefined时,默认为全局对象
  ctx = ctx || window
  // 就单纯为了生成一个ctx对象的key,当然写死也可以
  const fn = Symbol()
  // 这里的this是指调用myCall方法的函数对象,比如:test.myCall(obj, arg1, arg2)中的test函数
  ctx[fn] = this
  // 执行ctx对象里的fn方法
  const res = ctx[fn](...args)
  // 从ctx对象上删除fn属性,不然会改变传递进来的ctx对象
  delete ctx[fn]
  // 返回函数执行的结果
  return res
}

// 示例代码
const obj = {
  name: 'I am obj'
}
function test (arg1, arg2) {
  return `${this.name}, ${arg1} ${arg2}`
}
const res = test.myCall(obj, 'hello', 'world !!')
console.log(res)  // I am obj,hello world !!