zl程序教程

您现在的位置是:首页 >  前端

当前栏目

JavaScript中的prototype.bind()方法介绍

JavaScript方法 介绍 bind prototype
2023-06-13 09:15:24 时间

以前,你可能会直接设置self=this或者that=this等等,这样做当然也能起作用,但是使用Function.prototype.bind()会更好,看上去也更专业。
下面举个简单的例子:

复制代码代码如下:


varmyObj={
   specialFunction:function(){
   },
   anotherSpecialFunction:function(){
   },
   getAsyncData:function(cb){
       cb();
   },
   render:function(){
       varthat=this;
       this.getAsyncData(function(){
           that.specialFunction();
           that.anotherSpecialFunction();
       });
   }
};
myObj.render();

在这个例子中,为了保持myObj上下文,设置了一个变量that=this,这样是可行的,但是没有使用Function.prototype.bind()看着更整洁:
复制代码代码如下:

render:function(){
   this.getAsyncData(function(){
       this.specialFunction();
       this.anotherSpecialFunction();
   }.bind(this));
}

在调用.bind()时,它会简单的创建一个新的函数,然后把this传给这个函数。实现.bind()的代码大概是这样的:

复制代码代码如下:Function.prototype.bind=function(scope){
   varfn=this;
   returnfunction(){
       returnfn.apply(scope);
   };
}
 

下面在看一个简单的使用Function.prototype.bind()的例子:

复制代码代码如下:
varfoo={
   x:3
};

varbar=function(){
   console.log(this.x);
};

bar();//undefined

varboundFunc=bar.bind(foo);

boundFunc();//3
 

是不是很好用呢!不过遗憾的是IE8及以下的IE浏览器并不支持Function.prototype.bind()。支持的浏览器有Chrome7+,Firefox4.0+,IE9+,Opera11.60+,Safari5.1.4+。虽然IE8/7/6等浏览器不支持,但是Mozilla开发组为老版本的IE浏览器写了一个功能类似的函数,代码如下:

复制代码代码如下:
if(!Function.prototype.bind){
 Function.prototype.bind=function(oThis){
   if(typeofthis!=="function"){
     //closestthingpossibletotheECMAScript5internalIsCallablefunction
     thrownewTypeError("Function.prototype.bind-whatistryingtobeboundisnotcallable");
   }

   varaArgs=Array.prototype.slice.call(arguments,1),
       fToBind=this,
       fNOP=function(){},
       fBound=function(){
         returnfToBind.apply(thisinstanceoffNOP&&oThis
                                ?this
                                :oThis,
                              aArgs.concat(Array.prototype.slice.call(arguments)));
       };

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

   returnfBound;
 };
}