主题
call & bind
call
js
Function.prototype.myCall = function (ctx, ...args) {
ctx = ctx === null || ctx === undefined ? globalThis : Object(ctx)
const fn = this
const key = Symbol()
Object.defineProperty(ctx, key, {
value: fn,
enumerable: false,
})
ctx[key] = fn
const r = ctx[key](...args)
delete ctx[key]
return r
}bind
js
Function.prototype.myBind = function (ctx, ...args) {
const fn = this
return function (...restArgs) {
if (new.target) {
return new fn(...args, ...restArgs)
}
return fn.apply(ctx, [...args, ...restArgs])
}
}