手写JavaScript-call、apply、bind方法

101 阅读1分钟

手写call方法

Function.prototype.ownCall = function(context, ...args) {
  console.log(context)
  console.log(this, ...args)
  context.fn = this
  const res = context.fn(...args)
  delete context.fn
  return res
}

function add(x, y) {
  console.log(this)
  return x + y
}

const obj = {}

const res = add.ownCall(obj, 1, 2)
console.log(res)
console.log(obj)

手写apply方法

Function.prototype.ownApply = function(context, args) {
  context.fn = this
  const res = context.fn(...args)
  delete context.fn
  return res
}

const obj = {}
function add(x, y) {
  console.log(this)
  return x + y
}

const res = add.ownApply(obj, [1, 2])
console.log(res)

手写bind方法


Function.prototype.ownBind = function(context, ...args) {
  context.fn = this
  return function() {
    const rv = context.fn(...args)
    delete context.fn
    return rv
  }
}

function add(x, y) {
  console.log(this)
  return x + y
}

const obj = {}

const newAdd = add.ownBind(obj, 1, 2)
const res = newAdd(1, 2)
console.log(res)