javascript中bind函数的作用实例介绍
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8">
<style>
button{background-color:#0f0;}
</style>
</head>
<body>
<buttonid="button">按钮</button>
<inputtype="text">
<script>
varbutton=document.getElementById("button");
button.onclick=function(){
alert(this.id);//弹出button
};
//可以看出上下文的this为button
</script>
</body>
</html>
此时加入bind
vartext=document.getElementById("text");
varbutton=document.getElementById("button");
button.onclick=function(){
alert(this.id);//弹出button
}.bind(text);
//可以看出上下文的this为button
此时会发现this改变为text
函数字面量里也适用,目的是保持上下指向(this)不变。
varobj={
color:"#ccc",
element:document.getElementById('text'),
events:function(){
document.getElementById("button").addEventListener("click",function(e){
console.log(this);
this.element.style.color=this.color;
}.bind(this))
returnthis;
},
init:function(){
this.events();
}
};
obj.init();
此时点击按钮text里的字会变色。可见this不为button而是obj。
bind()的方法在ie,6,7,8中不适用,需要扩展通过扩展Functionprototype可以实现此方法。
if(!Function.prototype.bind){
Function.prototype.bind=function(obj){
varslice=[].slice,args=slice.call(arguments,1),self=this,nop=function(){
},bound=function(){
returnself.apply(thisinstanceofnop?this:(obj||{}),
args.concat(slice.call(arguments)));
};
nop.prototype=self.prototype;
bound.prototype=newnop();
returnbound;
};
}
此时可以看到ie6,7,8中也支持bind()。
slice=Array.prototype.slice, 或 array=Array.prototype.slice.call(array,0);
将类似数组转换为数组