bind() 函数兼容

为了搞清这个陌生又熟悉的bind,google一下,发现javascript1.8.5版本中原生实现了此方法,目前IE9+,ff4+,chrome7+支持此方法,opera和safari不支持(MDN上的说明)。 
bind的作用和apply,call类似都是改变函数的execute context,也就是 runtime 时 this 关键字的指向。但是使用方法略有不同。一个函数进行bind后可稍后执行。

 bind 方法实现:绑定this  和 “科里化”:

function getConfig(colors,size,otherOptions){

  console.log(colors,size,otherOptions)

}

var defaultConfig = getConfig.bind(null,"#f00","1024*768");

defaultConfig("123");  //#f00 1024*768 123

defaultConfig("345");  //#f00 1024*768 345

因为bind 方法是EMS5 以后提出的方法,对于老的浏览器,可以使用手写一个bind 方法

if(!Function.prototype.bind){

  Function.prototype.bind = function(oThis){

    if(typeOf this !== 'function'){

      throw new TypeError('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?this:oThis,

           aArgs.concat(Array.prototype.slice.call(arguments)))

      }

    fNOP.prototype = this.prototype;

    fBound.prototype = new fNOP();

    return fBound;

  }

}

转载于:https://www.cnblogs.com/leong-min/p/6163961.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值