码迷,mamicode.com
首页 > 其他好文 > 详细

bind() 函数兼容

时间:2016-12-12 14:57:03      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:etc   支持   get   bsp   exec   bin   cti   getconf   chrome   

为了搞清这个陌生又熟悉的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;

  }

}

bind() 函数兼容

标签:etc   支持   get   bsp   exec   bin   cti   getconf   chrome   

原文地址:http://www.cnblogs.com/leong-min/p/6163961.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!