js中bind函数的实现

今天研究了一下es5中的bind函数如何用es3的语法来实现,下面是一个简单的bind函数实现:

bind函数

Function.prototype.bind=function(oThis){
    var self=this;
    var args=Array.prototype.slice.call(arguments,1);
    var result=function(){
        return self.apply(oThis,args.concat(Array.prototype.slice.call(arguments)));
    };

    var temp=function(){};
    temp.prototype=this.prototype;
    result.prototype=new temp();
    return result;
};

测试代码

var A={
    name: 'jc',
    print: function(title){
        console.log(title+this.name);
    }
};

var func=A.print.myBind(A);
func('red');   //jcred

分析

整个bind函数一共做了两件事:

  1. 首先通过数组的原型方法把bind函数参数中除了oThis对象以外的参数保存到args中,然后再讲args和调用函数传入参数列表合并,并通过调用Function.prototype.apply方法将oThis绑定到调用函数的this上,并传入合并后的参数列表。

  2. 因为调用apply方法返回了一个新的函数对象,丢失了原函数对象的原型属性,所以还要将新的函数对象的prototype属性引用原函数对象的原型对象。

  3. 之所以不采用result.prototype=this.prototype这种写法,而是使用了一个中间层对象temp,是因为不想通过修改result.prototype就修改了原函数对象的原型对象。

附上bind函数官方文档的实现

if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }

    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                                 ? this
                                 : oThis || window,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };

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

    return fBound;
  };
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • title: js面向对象date: 2017年8月17日 18:58:05updated: 2017年8月27日...
    lu900618阅读 581评论 0 2
  • 前言: 本来只是想写一下简单的 bind 函数实现,没想到写着写着还能牵出 js 中继承的知识,其实研究原生函数的...
    极乐君阅读 2,803评论 0 3
  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 7,854评论 2 17
  • 单例模式 适用场景:可能会在场景中使用到对象,但只有一个实例,加载时并不主动创建,需要时才创建 最常见的单例模式,...
    Obeing阅读 2,110评论 1 10
  • 对于父亲,我内心是矛盾和充满期待的。矛盾是自己无法坦然地将其美化,去赞美歌颂他。期待是自己内心还是挺渴求父亲能和其...
    袖子_阅读 334评论 0 0