Skip to content

functionBind

手动实现的 Function.prototype.bind,用于绑定函数的 this 上下文和部分参数。

函数签名

typescript
// bind 函数
function myBind<T extends (...args: any[]) => any>(
  fn: T,
  context: any,
  ...args: any[]
): (...remainingArgs: any[]) => ReturnType<T>

// call 函数
function myCall<T extends (...args: any[]) => any>(
  func: T,
  thisArg: any,
  ...args: Parameters<T>
): ReturnType<T>

// apply 函数
function myApply<T extends (...args: any[]) => any>(
  func: T,
  thisArg: any,
  args?: Parameters<T>
): ReturnType<T>

参数

myCall

参数名类型必填说明
funcFunction要调用的函数
thisArgany要绑定的 this 上下文
...argsany[]函数参数

myApply

参数名类型必填说明
funcFunction要调用的函数
thisArgany要绑定的 this 上下文
argsany[]函数参数数组

myBind

参数名类型必填说明
fnFunction要绑定的函数
contextany要绑定的 this 上下文
...argsany[]预先绑定的参数

返回值

函数类型说明
myCallReturnType<T>函数执行结果
myApplyReturnType<T>函数执行结果
myBindFunction绑定后的新函数

工作原理

myCall

  1. 处理 null/undefined 的 thisArg,使用全局对象(兼容浏览器/Node.js)
  2. 创建唯一的 Symbol 键,避免属性冲突
  3. 将函数临时添加为 context 的属性
  4. 调用该属性(自动绑定 this)
  5. 删除临时属性
  6. 返回执行结果

myApply

  1. 与 myCall 类似
  2. 区别是参数以数组形式传入

myBind

  1. 保存原函数、上下文和预绑定参数
  2. 返回新函数:
    • 检查是否被 new 调用
    • 如果是 new 调用:使用新对象作为 this
    • 否则:使用绑定的 context
    • 合并预绑定参数和新参数
    • 调用原函数
  3. 维护原型链(支持 new 调用)

模拟原生 Function.prototype 方法的行为,所有环境兼容性都在函数内部处理。