js中this的用法

查看this指向的一句话法则:
*
 
永远指向其所在函数的所有者如果没有所有者时,指向window。
*理解this的要点:关键在于将函数与函数名分开看待。同一个函数,在不同的执行方法下,会有不同的效果
 
如何来进行理解呢,来看几个实例
1)全局函数中的this指向

function test(){
alert(this);//test这个函数没有所有者,因此此时this指向的是window
}

2)对象方法中的this指向

o.test = function(){

alert(this==o);//输出true,o.test表示的是test这个函数的所有者是对象o,因此this应当是指向o的

}

3)绑定函数时的this 1
如下代码,test1和test2中this并不相同

var test2 = o.test1;//test2这个函数并没有所有者,在此,test2虽然调用了test1这个函数,但是this仍然指向window,而不是指向test1的拥有者:对象o
test2();
o.test1 = function(){

alert(this===o);

}

这便是上面所说的,要将函数与函数名分开看待
4)绑定函数时的this 2
此时如果我们对3)中的代码进行一些修改:

function test () {
alert(this === o);
}
test();//this指向window
var o = {};
o.test2 = test;
o.test2();//此时test2的所有者为o,而test没有所有者,this在此时指向的是o
alert(o.test2);

5)鼠标单击事件等进行函数的绑定时,this的指向

document.onclick=function(){

alert(this===document);//输出为true,onclick事件的拥有者是document。因此,此处this指向document。我们可以将document.onclick理解为一个对象方法,如同例4中的o.test2一样。

}

6)setTimeout等传参形式的this指向
不要去看传的参数中函数的所有者,看执行函数的所有var obj = {};

obj.x = 1;
obj.y = 2;
window.x = 100;
window.y = 200;
obj.add = function () {
alert(this.x + this.y);
}
setTimeout(obj.add,1000);//this指向window,输出为300
setTimeout(function(){//this指向obj,输出为3
obj.add();
},1000);

改变this的方法:call,apply
call和apply(两者用于改变函数的作用域)

var oo = {};
oo.test3 = function(){
alert(this == oo);//返回false
}
var ooo = {};
oo.test3.call(ooo);//this指向的是()内的第一个参数,此处为ooo


window.x = 100;
var oo = {};

oo.test3 = function(y,z,k){//函数的参数与apply、call中第二个以及之后的参数相对应
alert(this.x+y+z+k);
}
var arr=[2,3,4]
oo.test3.call(window,2,3,4);//this指向window,输出为109
oo.test3.apply(window,[2,3,4]);//同上,使用apply进行元素罗列时需要使用中括号[]将所有参数包裹起来
oo.test3.apply(window,arr);//同上,使用apply对于一个数组的访问很简单,使用数组名称即可
oo.test3.call(window,arr[0],arr[1],arr[2]);//同上

blog首页:http://www.cnblogs.com/hubgit/
原文地址:https://www.cnblogs.com/hubgit/p/5732110.html