js改变this指向的方法及之间差别
再说具体方法之前提一嘴:
如果函数中,又包含一个函数(闭包),则内部函数的this指向为window
一.改变this的方法:
1.赋值:
var userName ="张三"; //window对象添加了一个userName属性值为 ==》张三
var obj = {
userName:"李四",
run:function(){
//this===》obj
return function(){
//this===>window
return this.userName; //闭包。
};
}
}
alert( obj.run()() );//输出张三
把指向obj对象的this赋值给that
var userName ="张三"; //window对象添加了一个userName属性值为 ==》张三
var obj = {
userName:"李四",
run:function(){
var That = this; //this==>obj
return function(){
return That.userName; // 返回的结果是李四
};
}
}
alert( obj.run()() );//输出李四
2.利用apply和call方法:
相同之处:
作用相同,都是改变this指向
不同之处:
语法:
call: 方法.call(对象,参数1,参数2,参数3…) call参数是一个一个挨着写的
apply:方法.apply(对象,[参数1,参数2,参数…]) apply是2个参数,第二个参数是一个大数组
function add(c, d){
return this.a + this.b + c + d;
}
var o = {a:1, b:3};
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
3.bind()的用法,有个博主写的很详细,比我整理的好,我就转载一下了
-----------------------------------------------------------------------------------------------------
再说一个使用,apply的小技巧:
众所周知:
Math.min()函数,里面的参数,必须是数值
alert( Math.min(3,2,4,5,6,6) );//输出2
var arr = [3,2,4,5,6];
alert( Math.min(arr) );//会报错
但是我们必须用arr进行比较怎么办呢,利用apply()
var arr = [31,99,44,51,66];
alert( Math.min.apply(window,arr) );
正好apply传的是数组,利用了这个特性