Function.prototype.call 实现原理

Function.prototype.call

方法说明javascript

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

源码的关键点在于java

在传递进来的上下文对象中构造一个须要执行的方法,好比:
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 !!
相关文章
相关标签/搜索