手写实现call方法:
核心逻辑是:要改变当前this指向第一个参数obj,实际上是通过在obj对象中添加一个调用函数this. this在这里是函数的调用对像,比如:obj.fn,this就是obj.
// // 手写call
Function.prototype.callFn=function(obj,...args){
// 如果第一个参数不存在,则创建一个空对象
if(!obj) obj=Object.create(null)
// 相当于在obj内部增加一个函数。
obj.fn=this
// 将obj中新增的函数对象赋值到res中
const res=obj.fn(...args)
// 首次调用一次
obj.fn(...args)
// 删除obj对象中增加的函数对象
delete obj.fn
return res
}
function sum (a,b){
return this.v+a+b
}
console.log(sum.callFn({v:3},2,3))
手写实现apply:
apply的特点是传入的剩余参数是一个数组对象
// 手写实现apply
Function.prototype.applyFn=function(_this,args){
// 不是对象创建一个空对象
if( !_this)Object.create(null)
//作用域添加函数对象
_this.fn=this
const res=_this.fn(...args)
// 删除添加的fn
delete _this.fn
return res
}
const v=1
function sum (a,b){
return this.v+a+b
}
console.log(sum.applyFn({v:10},[2,3]))
简单实现,后续更新.....