如果了解他们的作用请参考我的上一篇博客 js中Function对象–call、apply和bind
call
Function.prototype.myCall = function (obj) {
const args = [...arguments].splice(1) // 拿到除了第一个参数外的所有参数,并使其变成数组。
obj.temp = this // 这里的this就是调用这个myCall的函数,下面的test函数,我们把这个函数赋给了obj的一个临时属性。
obj.temp(...args) // 这个时候我们在执行这个obj.temp 函数的this就变成了obj
delete obj.temp
}
function test(a){
console.log(a,this.name)
}
const obj = { id: 1, name: 'zs' }
test.myCall(obj,1) // 1, 'zs'
apply
Function.prototype.myApply = function (obj, arr) {
obj.temp = this
obj.temp(...arr)
delete obj.temp
}
apply的实现原理跟call类似,就是第二个参数变成了一个数组。
bind
bind有使用有两个方式,实现起来稍微复杂一点,bind的参数可以在使用bind是传,也可以在返回的函数中传.
// 1.
const action = test.bind(obj, 1)
action() // 1,'zs'
// 2.
const action = test.bind(obj)
action(1) // 1,'zs'
实现:
Function.prototype.myBind = function(obj, arr) {
let args = [...arguments].splice(1) // 调用myBind的传入的参数
const self = this // 保存一下这个this,为当前调用函数test
return function() {
console.log(arguments)
const inArgs = [...arguments] // 返回的函数的参数.
if(arguments.length > 0) {
args = [...args, ...inArgs] // 把两次传入的参数都放入这个数组中。
}
self.apply(obj, args) // 内部调用apply实现
}
}
const action = test.myBind(obj, 1)
action() // 1,'zs'
const action = test.myBind(obj)
action(1) // 1,'zs'