js--api--bind模拟实现

js--api--bind模拟实现


  • 微信扫码关注公众号 :前端前端大前端,追求更精致的阅读体验 ,一起来学习啊
  • 关注后发送关键资料,免费获取一整套前端系统学习资料和老男孩python系列课程
    在这里插入图片描述

desc

上一篇介绍了call/apply的实现,这里说一下bind的模拟,其实bind的作用和call/apply类似,都可以改变this指向,不同的是,bind执行后返回的是一个函数,并不会自己调用
mdn上这样解释:bind()方法创建一个新的函数,在bind()被调用时,这个新函数的this被bind的第一个参数指定,其余的参数将作为新函数的参数供调用时使用。

var stu = {
  name:"tom",
  age: 18,
};

function say() {
  console.log(`my name is ${this.name},${this.age} years old`);
}

var bindSay=say.bind(stu); 
bindSay();// my name is tom,18 years old

在这里插入图片描述

code

/**
 * * 改变this指向
 * * 返回一个函数
 * * 可传参
 * * 柯里化
 */


Function.prototype.bind = function (context, ...args) {

  if (typeof this !== "function") {
    throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
  }

  let self = this
  let MiddleFn = function () { }
  let BindFn = function (...rest) {
    return self.apply(this instanceof BindFn ? this : context, args.concat(rest));
  }

  MiddleFn.prototype = this.prototype
  BindFn.prototype = new MiddleFn()
  return BindFn;
}


发布了396 篇原创文章 · 获赞 786 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/qq_42813491/article/details/103080260