手写call&apply&bind
在这里对call,apply,bind函数进行简单的封装
封装主要思想:给对象一个临时函数来调用,调用完毕后删除该临时函数对应的属性
call函数封装
function pliCall(fn, obj, ...args) {
if (obj === undefined || obj === null) {
obj = globalThis
}
obj.temp = fn
let result = obj.temp(...args)
delete obj.temp
return result
}
apply函数
function pliApply(fn, obj, args) {
if (obj === undefined || obj === null) {
obj = globalThis
}
obj.temp = fn;
let result = obj.temp(...args)
delete obj.temp
return result
}
bind函数
需要注意的是bind()返回的是一个可执行函数
function pliBind(fn, obj, ...args) {
return function (...args2) {
if (obj === undefined || obj === null) {
obj = globalThis
}
obj.temp = fn;
let result = obj.temp(...args, ...args2)
delete obj.temp;
return result
}
}
以上为本阶段学习的一点理解,以后若接触到更多会逐步添加…