本文共 1906 字,大约阅读时间需要 6 分钟。
我一同学总结的关于this的用法,个人感觉总结的挺全面的,和大家分享一下。
原文:
从自己刚刚开始学习javascript到现在已经很久了,今天得益于新酱的细心讲解,总算是把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 1var test2 = o.test1;//test2这个函数并没有所有者,在此,test2虽然调用了test1这个函数,但是this仍然指向window,而不是指向test1的拥有者:对象o
test2();o.test1 =function(){alert(this===o);
}
这便是上面所说的,要将函数与函数名分开看待function test (){
alert(this=== o);}test();//this指向windowvar o ={};o.test2 = test;o.test2();//此时test2的所有者为o,而test没有所有者,this在此时指向的是oalert(o.test2); 5)鼠标单击事件等进行函数的绑定时,this的指向document.onclick=function(){
alert(this===document);//输出为true,onclick事件的拥有者是document。因此,此处this指向document。我们可以将document.onclick理解为一个对象方法,如同例4中的o.test2一样。
}
6)setTimeout等传参形式的this指向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,输出为300setTimeout(function(){ //this指向obj,输出为3obj.add();},1000);var oo ={};
oo.test3 =function(){ alert(this== oo);//返回false}var ooo ={};oo.test3.call(ooo);//this指向的是()内的第一个参数,此处为ooowindow.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,输出为109oo.test3.apply(window,[2,3,4]);//同上,使用apply进行元素罗列时需要使用中括号[]将所有参数包裹起来oo.test3.apply(window,arr);//同上,使用apply对于一个数组的访问很简单,使用数组名称即可oo.test3.call(window,arr[0],arr[1],arr[2]);//同上本文转自挨踢前端博客园博客,原文链接http://www.cnblogs.com/duanhuajian/archive/2012/09/23/2699143.html如需转载请自行联系原作者
@挨踢前端