查看JavaScript中this指向的对象,this指向的一句话法则:数组
永远指向其所在函数的全部者若是没有全部者时,指向window。app
理解this的要点:关键在于将函数与函数名分开看待。同一个函数,在不一样的执行方法下,会有不一样的效果。函数
废话很少说,多说的都是废话,不要看,这一句也是废话,哈哈,我真能自娱自乐,come on下面直接上例子:this
1)全局函数中的this指向spa
function test(){ alert(this);//test这个函数没有全部者,所以此时this指向的是window
}
2)对象方法中的this指向code
wang.test = function(){ alert(this==wang);//输出true,wang.test表示的是test这个函数的全部者是对象wang,所以this应当是指向wang的
}
3)绑定函数时的this对象
以下代码,test1和test2中this并不相同blog
var test2 = wang.test1;
//test2这个函数并无全部者,在此,test2虽然调用了test1这个函数,可是this仍然指向window,而不是指向test1的拥有者:对象wang
test2(); wang.test1 = function(){ alert(this===wang); }
这即是上面所说的,要将函数与函数名分开看待事件
4)绑定函数时的thisip
此时若是咱们对3)中的代码进行一些修改:
function test () { alert(this === wang); } test();//this指向window
var wang= {}; wang.test2 = test; wang.test2();//此时test2的全部者为wang,而test没有全部者,this在此时指向的是wang
alert(wang.test2);
5)鼠标单击事件等进行函数的绑定时,this的指向
document.onclick=function(){ alert(this===document);
//输出为true,onclick事件的拥有者是document。所以,此处this指向document。
咱们能够将document.onclick理解为一个对象方法,如同例4中的w.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);
7)改变this的方法:call,apply
call和apply(二者用于改变函数的做用域)
var wang= {}; wang.test3 = function(){ alert(this == wang);//返回false
} var my= {}; wang.test3.call(my);//this指向的是()内的第一个参数,此处为my
window.x = 100; var wang= {}; wang.test3 = function(y,z,k){//函数的参数与apply、call中第二个以及以后的参数相对应
alert(this.x+y+z+k); } var arr=[2,3,4] wang.test3.call(window,2,3,4);//this指向window,输出为109
wang.test3.apply(window,[2,3,4]);//同上,使用apply进行元素罗列时须要使用中括号[]将全部参数包裹起来
wang.test3.apply(window,arr);//同上,使用apply对于一个数组的访问很简单,使用数组名称便可
wang.test3.call(window,arr[0],arr[1],arr[2]);//同上