上一章this的显式绑定我们用到了apply,call和bind函数,我有点好奇为什么它可以改变this的指向,所以经过一番研究和查找资料,我整理了他们的内部代码实现。
call
Function.prototype.mycall = function(thisArg, ...args) {
let fn = this // 这里的this指向的是外部调用的函数对象,即隐式绑定。
thisArg = thisArg ? Object(thisArg) : window// 防止传入的是数字,字符串,布尔值等
thisArg.fn = fn // 如果有thisArg,那么把this指向thisArg
thisArg.fn(...args)
delete thisArg.fn // fn不需要所以删除
}
apply
Function.prototype.myapply = function(thisArg, argArray) {
let fn = this // 这里的this指向的是外部调用的函数对象,即隐式绑定。
thisArg = thisArg ? Object(thisArg) : window// 防止传入的是数字,字符串,布尔值等
thisArg.fn = fn // 如果有thisArg,那么把this指向thisArg
thisArg.fn(argArray)
delete thisArg.fn // fn不需要所以删除
}
apply和call的唯一区别就是传参方式不同,所以代码基本一样。
bind
Function.prototype.mybind = function(thisArg, ...argArray) {
let fn = this
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : thisArg
return function(...otherArg) {
thisArg.fn = fn
let res = thisArg.fn(...otherArg, ...argArray) // 柯里化函数
delete thisArg.fn
return res
}
}