关于javascript:手写JS函数的callapplybind

9次阅读

共计 2129 个字符,预计需要花费 6 分钟才能阅读完成。

之所以要写这篇,是因为已经面试被要求在白纸上手写 bind 实现

  后果跟代码一样清晰明确,一阵懵逼, 没写进去!

  上面,撸起袖子就是干!~

  把 call、apply、bind 一条龙都整一遍!~~

call

定义与应用

Function.prototype.call(): developer.mozilla.org/zh-CN/docs/…

// Function.prototype.call() 样例
function fun(arg1, arg2) {console.log(this.name)
  console.log(arg1 + arg2)
}
const _this = {name: 'YIYING'}
// 承受的是一个参数列表; 办法立刻执行
fun.call(_this, 1, 2)
// 输入:YIYING
3

手写实现

/** * 自定义 call 实现 * @param context   上下文 this 对象 * @param args      动静参数 */
Function.prototype.ownCall = function(context, ...args) {context = (typeof context === 'object' ? context : window)
  // 避免笼罩掉原有属性
  const key = Symbol()
  // 这里的 this 为须要执行的办法
  context[key] = this
  // 办法执行
  const result = context[key](...args)
  delete context[key]
  return result
}
// 验证样例
function fun(arg1, arg2) {console.log(this.name)
  console.log(arg1 + arg2)
}
const _this = {name: 'YIYING'}
// 承受的是一个参数列表; 办法立刻执行
fun.ownCall(_this, 1, 2)
// 输入:YIYING
3

apply

定义与应用

Function.prototype.apply(): developer.mozilla.org/zh-CN/docs/…

// Function.prototype.apply() 样例
function fun(arg1, arg2) {console.log(this.name)
  console.log(arg1 + arg2)
}
const _this = {name: 'YIYING'}
// 参数为数组; 办法立刻执行
fun.apply(_this, [1, 2])
// 输入:YIYING
3

手写实现

/** * 自定义 Apply 实现 * @param context   上下文 this 对象 * @param args      参数数组 */
Function.prototype.ownApply = function(context, args) {context = (typeof context === 'object' ? context : window)
  // 避免笼罩掉原有属性
  const key = Symbol()
  // 这里的 this 为须要执行的办法
  context[key] = this
  // 办法执行
  const result = context[key](...args)
  delete context[key]
  return result
}
// 验证样例
function fun(arg1, arg2) {console.log(this.name)
  console.log(arg1 + arg2)
}
const _this = {name: 'YIYING'}
// 参数为数组; 办法立刻执行
fun.ownApply(_this, [1, 2])
// 输入:YIYING
3

bind

定义与应用

Function.prototype.bind()
: developer.mozilla.org/zh-CN/docs/…

// Function.prototype.bind() 样例
function fun(arg1, arg2) {console.log(this.name)
  console.log(arg1 + arg2)
}
const _this = {name: 'YIYING'}
// 只变更 fun 中的 this 指向,返回新 function 对象
const newFun = fun.bind(_this)
newFun(1, 2)
// 输入:YIYING
3

参考 前端进阶面试题具体解答

手写实现

/** * 自定义 bind 实现 * @param context     上下文 * @returns {Function} */
Function.prototype.ownBind = function(context) {context = (typeof context === 'object' ? context : window)
  return (...args)=>{this.call(context, ...args)
  }
}
// 验证样例
function fun(arg1, arg2) {console.log(this.name)
  console.log(arg1 + arg2)
}
const _this = {name: 'YIYING'}
// 只变更 fun 中的 this 指向,返回新 function 对象
const newFun = fun.ownBind(_this)
newFun(1, 2)
// 输入:YIYING
3
正文完
 0