Loading

「跟着渡一学前端」手写bind函数

完整代码

Function.prototype.myBind = function (ctx, ...args) {
  const fn = this;
  return function (...resArgs) {
    if (new.target) {
      return new fn(...args, ...resArgs);
    }
    return fn.apply(ctx, [...args, ...resArgs]);
  }
}

function fn(a,b,c,d,e){
  console.log(this);
  console.log(a,b,c,d,e);
}

const newFn=fn.myBind(1,2,3);
const r=new newFn(3,6,7);

知识详情

  1. 函数写哪?——写到函数原型上(即Function.prototype),让所有函数都具有这个方法
  2. 参数确定:第一个参数接收this值,然后通过解构收集剩下参数用作参数专递。
  3. 确定返回内容:需要返回一个新的函数,新的函数内部也会有参数,定义一个新变量resArgs解构收集
  4. 绑定this:
    1. 确定this获取this:调用newFn时,相当于在调用fn(即第二行代码获取this)。
    2. 绑定this(即第7行代码)
  5. 考虑原函数的返回值——需要返回绑定this后的函数。(即第7行代码加上return返回值)
  6. 考虑调用可能通过new调用——通过new.target来判断是否通过new调用。
    • 如果是new 调用则,new.target为new的函数
    • 否则为undefined
posted @ 2025-02-16 20:19  lao-jiawei  阅读(30)  评论(0)    收藏  举报