Skip to content

Latest commit

 

History

History
61 lines (47 loc) · 1.23 KB

Call-apply-bind.md

File metadata and controls

61 lines (47 loc) · 1.23 KB
// https://github.com/mqyqingfeng/Blog/issues/11
/**
 * 
 * @param {*} ctx 函数执行上下文this
 * @param  {...any} args 参数列表
 * @returns 函数执行的结果
 */
Function.prototype.myCall = function (ctx, ...args) {
  if (!ctx) {  ctx = typeof window !== 'undefined' ? window : global}
  // 暴露处理 ctx有可能传非对象
  ctx = Object(ctx)

  const fnName = Symbol('key')
  ctx[ fnName ] = this
  const result = ctx[ fnName ](...args)
  delete ctx[ fnName ]
  return result
}

let fn = function (name, sex) {
  console.log(this, name, sex)
}

fn.myCall('', '111', 'boy'), 
fn.myCall({ name: '111', sex: 'boy' }, '111', 'boy')


/**
 * 
 * @param {*} ctx 函数执行上下文this
 * @param {*} args  数组
 * @returns 函数执行的结果
 */
Function.prototype.myApply = function (ctx, args) {
  if (!ctx) {
    ctx = typeof window !== 'undefined' ? window : global
  }
  // 暴露处理 ctx有可能传非对象
  ctx = Object(ctx)

  const fnName = Symbol()

  ctx[ fnName ] = this

  const result = ctx[ fnName ](...args)

  delete ctx[ fnName ]

  return result
}

let fn = function (name, sex) {
  console.log(this, name, sex)
}


fn.myApply('', ['111', 'boy'])
fn.myApply({ name: '111', sex: 'boy' }, ['111', 'boy'])