强制改变this指向(call,apply,bind的用法和区别)
call
格式:函数名.call();
参数:
第一个参数:传入该函数this指向的对象,转入什么强制指向什么
第二个参数开始将原有的参数往后顺延一位
function show(x,y){
alert(this);
alert(x + "," + y);
}
show(20,30); // [object Window] // 20,30
show.call("call",20,40); // call // 20,40
apply
格式:函数名.apply()
参数:
第一个参数:传入该函数this指向的对象,转入什么强制指向什么
第二个参数:数组 数组放入我们原有所有的参数
function show(x,y){
alert(this);
alert(x + "," + y);
}
show(20,30); // [object Window] // 20,30
show.apply("apply",[20,40]); // apply // 20,40
bind 预设this指向
var res = show.bind('bind');
alert(res) // function () { [native code] }
res(40,50) // bind // 40,50
//简写
show.bind('bind')(40,50)
apply方法使用的小技巧
Math.min(); // 传入所有参数中的最小值
Math.max(); // 传入所有参数中的最大值
//正常情况下(数字只能一个一个写入)
alert(Math.min(10,20,30,40,50));
alert(Math.max(10,20,30,40,50));
//是由apply方法(可以传入一个数组)
var arr = [10,20,30,40,50];
alert(Math.min.apply(null,arr));
alert(Math.max.apply(null,arr));