首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >day032: 能不能模拟实现一个 bind 的效果?

day032: 能不能模拟实现一个 bind 的效果?

作者头像
用户3806669
发布2021-03-11 14:39:40
发布2021-03-11 14:39:40
4240
举报
文章被收录于专栏:前端三元同学前端三元同学

实现bind之前,我们首先要知道它做了哪些事情。

  1. 对于普通函数,绑定this指向
  2. 对于构造函数,要保证原函数的原型对象上的属性不能丢失
代码语言:javascript
复制
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");
    }
    // 保存this的值,它代表调用 bind 的函数
    var self = this;
    var fNOP = function () {};

    var fbound = function () {
        self.apply(this instanceof self ?
            this :
            context, args.concat(Array.prototype.slice.call(arguments)));
    }

    fNOP.prototype = this.prototype;
    fbound.prototype = new fNOP();

    return fbound;
}

也可以这么用 Object.create 来处理原型:

代码语言:javascript
复制
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");
    }

    var self = this;

    var fbound = function () {
        self.apply(this instanceof self ?
            this :
            context, args.concat(Array.prototype.slice.call(arguments)));
    }

    fbound.prototype = Object.create(self.prototype);

    return fbound;
}
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-11-23,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档