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
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
func | Function | 是 | 要调用的函数 |
thisArg | any | 是 | 要绑定的 this 上下文 |
...args | any[] | 否 | 函数参数 |
myApply
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
func | Function | 是 | 要调用的函数 |
thisArg | any | 是 | 要绑定的 this 上下文 |
args | any[] | 否 | 函数参数数组 |
myBind
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
fn | Function | 是 | 要绑定的函数 |
context | any | 是 | 要绑定的 this 上下文 |
...args | any[] | 否 | 预先绑定的参数 |
返回值
| 函数 | 类型 | 说明 |
|---|---|---|
myCall | ReturnType<T> | 函数执行结果 |
myApply | ReturnType<T> | 函数执行结果 |
myBind | Function | 绑定后的新函数 |
工作原理
myCall
- 处理 null/undefined 的 thisArg,使用全局对象(兼容浏览器/Node.js)
- 创建唯一的 Symbol 键,避免属性冲突
- 将函数临时添加为 context 的属性
- 调用该属性(自动绑定 this)
- 删除临时属性
- 返回执行结果
myApply
- 与 myCall 类似
- 区别是参数以数组形式传入
myBind
- 保存原函数、上下文和预绑定参数
- 返回新函数:
- 检查是否被 new 调用
- 如果是 new 调用:使用新对象作为 this
- 否则:使用绑定的 context
- 合并预绑定参数和新参数
- 调用原函数
- 维护原型链(支持 new 调用)
模拟原生 Function.prototype 方法的行为,所有环境兼容性都在函数内部处理。