js自定义call bind

Function.prototype.mycall = function (ctx, ...args) {
  ctx = ctx === undefined || ctx === null ? globalThis : Object(ctx)
  const fn = this;
  const key = Symbol('temp')
  Object.defineProperty(ctx, key, {
    enumerable: false,
    value: fn
  })
  //ctx[key] = fn;
  const result = ctx[key](...args)
  delete ctx[key]
  return result
}

add.mycall("", 2, 3)

 

function forcall(fun) {
  console.log(fun)
  return function f1(...args) {
    console.log(11, args)
    if (args.length >= fun.length) {
      return fun(...args)
    } else {
      return (...moreargs) => {
        console.log(22, moreargs)
        const newargs = args.concat(moreargs)//[...args, ...moreargs] args.concat(moreargs)
        return f1(...newargs)
      }
    }
  }
}
function add(a, b, c) {
  return a + b + c;
}
// console.log(add.length)
// const aa = forcall(add)
// const ret = aa(2)(4)(3)
// console.log(ret)


function debounce(fun, duration = 500) {
  let timerId;
  return function (...args) {
    clearTimeout(timerId)
    timerId = setTimeout(() => {
      fun.apply(this, args)
    }, duration);
  }
}
function add(a, b) {
  console.log(a + b)
}
// const fun1 = debounce(add, 3000)
// fun1(2, 3)

Function.prototype.mybind = function (ctx) {
  const args = Array.prototype.slice.call(arguments, 1)
  const fn = this;
  return function bindFun() {
    const resArgs = Array.prototype.slice.call(arguments)
    const allArgs = args.concat(resArgs)
    if (Object.getPrototypeOf(this) === bindFun.prototype) {
      return new fn(...allArgs)
    } else {
      return fn.apply(ctx, allArgs)

    }
  }
}

function add(a, b) {
  console.log(a + b)
}

const ff = add.mybind('ctx', 3, 4)
ff(1, 2)

 

posted @ 2024-04-26 15:30  howhy  阅读(3)  评论(0编辑  收藏  举报