面试题之利用call或者apply实现bind功能

需求

利用call或者apply实现bind功能

分析

  1. 我们这里举例使用call来实现bind功能
  2. 既然最终实现的是bind功能,那就要先分析bind都具有什么功能
    • 根据函数生成新的函数
    • 改变期this指向
    • 传递第二个参数数组

实现步骤

1. 定义newBind方法
Function.prototype.newBind = function (obj) {
  return function () {
    
  }
}
2. 使用该方法
// 改变fn函数this指向obj
function fn() {
  console.log(this)
}  

var obj = {
  a: 1
}

const newFn = fn.newBind(obj)  // newFn相当于是newBind内部返回的函数
newFn()
3. 通过apply改变this指向
  • 改变newBind前面的函数的指向,所以在函数内部要拿到newBind前面的函数
Function.prototype.newBind = function (obj) {
  const that = this // 这个this就是newBind前面的函数
  return function () {
    that.call(obj)
  }
}
4. 接收参数,并将参数传递给期对应函数
function fn(nu1,num2) {
  console.log(nu1,num2,this)
}  
var obj = {
  a: 1
}

Function.prototype.newBind = function (obj) {
  const that = this 
  return function () {
    that.call(obj,...arguments)
  }
}

const newFn = fn.newBind(obj)
newFn(1,2)
5. 在return函数内添加部return

目的是用来接收改变期this指向的函数内部返回值

function fn(nu1,num2) {
  console.log(nu1,num2,this)
}  
var obj = {
  a: 1
}

Function.prototype.newBind = function (obj) {
  const that = this 
  console.log(that)
  return function () {
    return that.call(obj,...arguments)
  }
}

const newFn = fn.newBind(obj)
newFn(1,2)

猜你喜欢

转载自blog.csdn.net/weixin_41819098/article/details/106480096