手写 apply 方法
1. 函数作用
调用函数,可传入参数(数组),改变this指向
2. 总体步骤
- 边界判断(this, context, argArray)
- 将调用的函数设置为对象(传入的context)的方法(改变this指向)
- 调用函数,得到返回值,并返回
3. 详细步骤
1. 边界判断
- 判断当前
this
是否为一个函数,否则返回错误消息 - 判断是否传入
context
参数,存在则使用Object()
转换为对象赋给context
,否则将window
赋值给context
- 判断 是否传入
argArray
,没传等赋值为空数组
2. 将调用的函数设置为对象(传入的context)的方法(改变this指向)
3. 调用函数,得到返回值,并返回
- 调用函数,得到结果
- 删除
context
身上的fn
函数 - 返回结果
4. 代码实现
/** * !实现 binApply() 方法 * @param {*} context 绑定的对象 * @param {...any} argArray 数组 * @returns */ Function.prototype.binApply = function(context, argArray) { if (typeof this !== 'function') return console.error('Error') context = (context!==null && context!==undefined) ? Object(context) : window argArray = argArray || []
context.fn = this
const result = context.fn(...argArray) delete context.fn return result}
5. 测试代码
// 测试function sum(num1, num2) { console.log('sum 被执行', this); return num1 + num2}
// 原生的 apply() 方法console.log(sum.apply({name: 'bin'}, [1,2]));
// 自定义的 binApply() 方法console.log(sum.binApply({name: 'bin'}, [1,2]));
6. 细节解析
apply()
方法的第二个参数是数组this
指向的就是调用binApply()
的那个函数(隐式绑定);- 传入的
context
参数表示:将this
的指向改为这个参数; - 改变
this
指向其实就是在context
上添加一个临时的方法,值为this
; - 调用
context.fn()
时,就已经改变了this
的指向,同时得使用展开运算符传入参数 delete context.fn
删除那个临时方法是因为已经不需要用了
7. 核心原理
通过在传入的对象上,临时新增一个方法,这个方法的值是当前 binApply
的调用者。然后 context.fn(...argArray)
调用这个函数,通过隐式绑定的方式改变了 this
的指向,最后得到结果并返回
每文一句:古今来许多世家,无非积德。天地间第一人品,还是读书。
本次的分享就到这里,希望大家都能够有所收获。有任何疑问都可以在评论区留言,大家一起探讨、进步!