之所以要写这篇,是因为已经面试被要求在白纸上手写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)
// 输入:YIYING3

手写实现

/** * 自定义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)
// 输入:YIYING3

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])
// 输入:YIYING3

手写实现

/** * 自定义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])
// 输入:YIYING3

参考:前端手写面试题具体解答

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)
// 输入:YIYING3

手写实现

/** * 自定义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)
// 输入:YIYING3