438 字
1 分钟
手写 call、apply、bind
call、apply、bind 都是用来改变函数 this 指向的方法。理解它们的实现原理,对掌握 JavaScript 的 this 机制很有帮助。
先看用法
function greet(greeting) { console.log(`${greeting}, ${this.name}`)}
const user = { name: '张三' }
// call:逐个传参greet.call(user, '你好') // 你好, 张三
// apply:数组传参greet.apply(user, ['你好']) // 你好, 张三
// bind:返回新函数,不立即执行const bound = greet.bind(user, '你好')bound() // 你好, 张三三者的区别:
call:立即执行,参数逐个传递apply:立即执行,参数以数组传递bind:返回新函数,不立即执行
实现 call
核心思路:把函数挂到目标对象上,执行,然后删除。
Function.prototype.myCall = function (context, ...args) { // 1. 处理 context 为 null/undefined 的情况 context = context || globalThis
// 2. 防止属性名冲突,用 Symbol const fnKey = Symbol()
// 3. 把当前函数挂到 context 上 context[fnKey] = this
// 4. 执行函数 const result = context[fnKey](...args)
// 5. 删除临时属性 delete context[fnKey]
// 6. 返回结果 return result}测试:
function greet(greeting, punctuation) { return `${greeting}, ${this.name}${punctuation}`}
const user = { name: '张三' }
console.log(greet.myCall(user, '你好', '!')) // 你好, 张三!边界情况:
// context 为 null 时,this 指向 globalThisgreet.myCall(null, '你好') // this.name = undefined
// 原始类型会被包装greet.myCall(123, '你好') // Number 对象,this.name = undefined实现 apply
和 call 几乎一样,只是参数传递方式不同:
Function.prototype.myApply = function (context, args = []) { context = context || globalThis
const fnKey = Symbol() context[fnKey] = this
// 唯一区别:用展开运算符传数组 const result = context[fnKey](...args)
delete context[fnKey] return result}测试:
function greet(greeting, punctuation) { return `${greeting}, ${this.name}${punctuation}`}
const user = { name: '张三' }
console.log(greet.myApply(user, ['你好', '!'])) // 你好, 张三!实现 bind
bind 比较特殊,它返回一个新函数,而且需要处理两种情况:
- 返回的函数可以被
new调用 - 返回的函数也可以正常调用
Function.prototype.myBind = function (context, ...args) { const originalFn = this
return function boundFn(...innerArgs) { // 判断是否是 new 调用 // 如果是 new,this 应该指向新创建的实例,而不是 context if (this instanceof boundFn) { return new originalFn(...args, ...innerArgs) }
return originalFn.apply(context, [...args, ...innerArgs]) }}测试基本用法:
function greet(greeting, punctuation) { return `${greeting}, ${this.name}${punctuation}`}
const user = { name: '张三' }const bound = greet.myBind(user, '你好')
console.log(bound('!')) // 你好, 张三!测试 new 调用:
function Person(name, age) { this.name = name this.age = age}
const BoundPerson = Person.myBind(null, '张三')const p = new BoundPerson(18)
console.log(p.name) // 张三console.log(p.age) // 18console.log(p instanceof Person) // truebind 的完整实现
上面的实现有一个问题:instanceof 检测不够准确。更完善的实现:
Function.prototype.myBind = function (context, ...args) { if (typeof this !== 'function') { throw new TypeError('myBind must be called on a function') }
const originalFn = this
// 中间空函数,用于继承原型链 const NoOp = function () {}
const boundFn = function (...innerArgs) { // 判断是否是 new 调用 if (this instanceof NoOp) { return new originalFn(...args, ...innerArgs) } return originalFn.apply(context, [...args, ...innerArgs]) }
// 维护原型链 if (originalFn.prototype) { NoOp.prototype = originalFn.prototype } boundFn.prototype = new NoOp()
return boundFn}为什么需要 NoOp?
直接 boundFn.prototype = originalFn.prototype 会导致修改 boundFn 的 prototype 时影响到原函数。用空函数做中间层,切断引用关系。
实际应用场景
1. 类型检测
// 获取对象的真实类型Object.prototype.toString.call([]) // '[object Array]'Object.prototype.toString.call({}) // '[object Object]'Object.prototype.toString.call(null) // '[object Null]'2. 数组借用方法
// arguments 不是数组,没有 slice 方法function test() { // 借用 Array.prototype.slice const arr = Array.prototype.slice.call(arguments) console.log(arr) // [1, 2, 3]}test(1, 2, 3)3. 函数柯里化
function add(a, b, c) { return a + b + c}
// 用 bind 实现柯里化const add10 = add.bind(null, 10)console.log(add10(20, 30)) // 60
const add10and20 = add.bind(null, 10, 20)console.log(add10and20(30)) // 604. 绑定事件处理函数的 this
class Button { constructor() { this.text = '点击我' // bind 确保 handleClick 的 this 指向 Button 实例 document.querySelector('#btn') .addEventListener('click', this.handleClick.bind(this)) }
handleClick() { console.log(this.text) }}总结
| 方法 | 执行方式 | 参数 | 返回值 |
|---|---|---|---|
| call | 立即执行 | 逐个传递 | 函数返回值 |
| apply | 立即执行 | 数组传递 | 函数返回值 |
| bind | 不执行 | 逐个传递(可预设) | 新函数 |
实现思路:
- call/apply:把函数挂到目标对象上执行,执行完删除
- bind:返回闭包,内部判断是否 new 调用
写完这几个方法,对 this 的绑定规则会更清楚。
分享
如果这篇文章对你有帮助,欢迎分享给更多人!
手写 call、apply、bind
https://www.403bug.top/posts/handwrite-call-apply-bind/ 部分信息可能已经过时
相关文章 智能推荐





