JS实现new,call,apply,bind功能

58 阅读1分钟

new关键字实现

function _new(fn, ...arg) {
  const obj = Object.create(fn.prototype)
  const ret = fn.apply(obj, arg)
  return ret instanceof Object ? ret : obj
}

call函数实现

function _call(obj, ...params) {
  // this即为调用_call函数的对象
  if (obj === undefined || null) obj = window
  const sy = Symbol()
  obj[sy] = this
  const res = obj[sy](...params)
	delete obj[sy]
  return res
}
Function.prototype._call = _call

apply函数实现

// 和call实现差不多,仅仅是传参的不同
function _apply(obj, params) {
  if (Array.isArray(params) === false) throw new Error('params is not array')
	if (obj === undefined || null) obj = window
  const sy = Symbol()
  obj[sy] = this
  const res = obj[sy](...params)
  delete obj[sy]
  return res
}
Function.prototype._apply = _apply

bind函数实现

function _bind(obj, ...params) {
	const that = this
  const fn = function() {
    that.call(obj, ...params)
  }
  return fn
}
Function.prototype._bind = _bind