Skip to content

call & bind

call

https://v.douyin.com/i5V2PRh1/

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

https://v.douyin.com/i5V28UsS/

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])
  }
}

基于 MIT 许可发布