bind
- 返回的是一个函数
- 先拿到被 bind 的 function
- customBind 的挷定的参数和后传的参数并,用 apply 在 context 上应用
Funtion.prototype.customBind = function(context, ...args){
const self = this
return function(){
self.apply(context, [...args, ...arguments])
}
}
call
- customCall调用执行的,返回执行的结果
- 定义一个 symbol 属性,避免重复
context[fnKey] = this this 就是 xxx.call(obj, 'xx') 的 xxx
- 执行后 delete context[fnKey]
Function.prototype.customCall = function(context, ...args){
if(context === null) context = globalThis
if(typeof context !== 'object') context = new Object(context)
const fnKey = Symbol()
context[fnKey] = this
const res = context[fnKey](...args)
delete context[fnKey]
return res
}
apply
- customCall调用执行的,返回执行的结果
- 定义一个 symbol 属性,避免重复
context[fnKey] = this this 就是 xxx.call(obj, 'xx') 的 xxx
.、执行后 delete context[fnKey]
- 和自定义 call 不同的是 args 是一个数组
Function.prototype.customApply = function(context, args){
if(context === null) context = globalThis
if(typeof context !== 'object') context = new Object(context)
const fnKey = Symbol()
context[fnKey] = this
const res = context[fnKey](...args)
delete context[fnKey]
return res
}