手写 call 方法
1. 函数作用
调用函数,可传入参数,改变this指向
2. 总体步骤
- 边界判断(this,context)
- 将调用的函数设置为对象(传入的context)的方法(改变this指向)
- 调用函数,得到返回值,并返回
3. 详细步骤
1. 边界判断
- 判断当前
this
是否为一个函数,否则返回错误消息 - 判断传入的
context
参数是否存在,存在则使用Object()
转换为对象赋给context
,否则将window
赋值给context
2. 将调用的函数设置为对象(传入的context)的方法(改变this指向) 3. 调用函数,得到返回值,并返回
- 调用函数,得到结果
- 删除
context
身上的fn
函数 - 返回结果
4. 代码实现
/** * !实现 binCall() 方法 * @param {*} context 绑定的对象 * @param {...any} args 剩余参数 * @returns */Function.prototype.binCall = function(context, ...args) { if (typeof this !== 'function') console.error('type Error'); // 1 context = (context!==null && context!==undefined) ? Object(context) : window
context.fn = this // 2
const result = context.fn(...args) // 3 delete context.fn; return result}
5. 测试代码
// 测试function sum(num1, num2) { console.log('sum 被执行', this); return num1 + num2}
// 原生的 call() 方法console.log(sum.call({name: 'bin'},1,2));
// 自定义的 binCall() 方法console.log(sum.binCall({name: 'bin'},1,2));
6. 细节解析
this
指向的就是调用binCall()
的那个函数(隐式绑定);- 传入的
context
参数表示:将this
的指向改为这个参数; - 改变
this
指向其实就是在context
上添加一个临时的方法,值为this
; - 调用
context.fn()
时,就已经改变了this
的指向,同时得使用展开运算符传入参数 delete context.fn
删除那个临时方法是因为已经不需要用了
7. 核心原理
通过在传入的对象上,临时新增一个方法,这个方法的值是当前 binCall
的调用者。然后 context.fn(...argArray)
调用这个函数,通过隐式绑定的方式改变了 this
的指向,最后得到结果并返回
每文一句:富贵必从勤苦得,男儿须读五车书。