Skip to main content

手写 call

参数(ctx,...args)

  1. 上下文 ctx 不存在默认 window
  2. 声明 ctx.fn 变量,并将 this(即 fn.myCall()中的调用者 fn)赋予 ctx.fn
    • fn 函数 拷贝到 ctx.fn,这样函数的 this 指向自动变成 ctx
  3. 调用新函数的到返回值 result
  4. 删除无用 ctx.fn 属性
  5. 返回 result
Function.prototype.myCall = function (ctx,...args) {
// 模仿浏览器(ctx 等于 fn.myCall(obj) 中的 obj)
ctx = ctx || window
// 将函数设为对象的属性 ctx.fn = fn (this等于fn.myCall(obj) 中的 fn)
ctx.fn = this
// 执行该函数 ctx.fn(参数)
let result = ctx.fn(...args)
// 删除该函数 delete ctx.fn
delete ctx.fn
return result
}

使用方法:

let obj = {
value: 1
}
function fn(a, b) {
console.log(this.value)
return a + b
}
fn.myCall(obj, 1, 2)