call
Function.prototype.myCall = function (ctx, ...args) {
ctx = ctx === null || ctx === undefined ? globalThis : Object(ctx)
const key = Symbol('fn')
ctx[key] = this
const res = ctx[key](...args)
delete ctx[key]
return res
}
const obj = {
name: 'zhangsan'
}
test.myCall(null)
test.myCall(2)
test.myCall(obj)
apply
Function.prototype.myApply = function (ctx, args) {
ctx = ctx === null || ctx === undefined ? globalThis : Object(ctx)
args = Array.isArray(args) ? args : []
const key = Symbol('fn')
ctx[key] = this
const res = ctx[key](...args)
delete ctx[key]
return res
}
bind
Function.prototype.myBind = function (ctx, ...args1) {
ctx = ctx === null || ctx === undefined ? globalThis : Object(ctx)
const key = Symbol('fn')
ctx[key] = this
return function (...args2) {
const res = ctx[key](...args1, ...args2)
delete ctx[key]
return res
}
}