理解js中bind方法的使用
提到bind方法,估计大家还会想到call方法、apply方法;它们都是Function对象内建的方法,它们的
第一个参数都是用来更改调用方法中this的指向
。
需要注意的是
bind
是返回新的函数,以便稍后调用
;
apply
、
call
则是立即调用原函数
。而今天我们主要讲解bind方法的理解与使用。
bind方法是EcmaScript5新增的方法,该方法在mdn上是这么介绍的:
bind()方法创建一个
新的函数(称为绑定函数)
, 当被调用时,将其this关键字设置为提供的值,在调用新函数时,在任何提供之前提供一个给定的参数序列。
语法:
fun
.bind(
thisArg
[,
arg1
[,
arg2
[, ...]]])
参数
arg1, arg2, ...表示:
当绑定函数被调用时,这些参数
将置于实参之前
传递给被绑定的方法。
例1:
this.name='jack';
var demo={
name:'rose',
getName:function(){return this.name}
}
console.log(demo.getName());//输出rose 这里this指向demo
var another=demo.getName;
console.log(another()); //输出jack 这里指向全局变量jack
//运用bind方法改变this指向
var another2=another.bind(demo);
console.log(another2());//输出rose 这里this指向demo对象
例2:
function a(){
return Array.prototype.slice.call(arguments); //将类数组转换为真正的数组
}
var b=a.bind(this,15,20);
alert(b()); //15,20
var s=b(25,30);
alert(s); //15,20,25,30
例3:
function add(a,b){
return a+b;
}
var newFoo=add.bind(this,3,4); //7
function add(a,b){
return a+b;
}
var a=3;
var b=4;
var newFoo=add.bind(this,a,b);
a=6;
b=7;
console.log(newFoo()); //
返回值仍然是7,因为bind()
绑定的是参数的值
,而不是实际变量的值。