this到底指向谁,这是一个很头疼的问题,经常我们会把他给搞混,实际上只要记住this的最终指向的是那个调用它的对象
全局函数中指向window
function show(){
alert(this);//输出window
}
show();
对象方法中指向该对象
var obj = {
name: "小明",
age: 18,
sex: '男',
showName: function(){
alert(this.name); //输出小明
}
}
事件绑定中,指向目标对象
window.onload = function(){
var oBtn = document.getElementById("btn1");
oBtn.onclick = function{
alert(this); //指向oBtn
}
}
通过call,apply,bind强行改变this的指向
function show(num1, num2){
alert(this);
alert(num1 + ', ' + num2)
}
show.call("call", 40, 50); //this变成call
show.apply("apply", [30, 40]); //this变成apply
show.bind("bind")(10, 20); //this变成bind
var a = {
user:"name",
fun:function(){
console.log(this.user); //name
}
}
a.fun();
这里的this指向的是对象a,因为你调用这个fun是通过a.fun()执行的,那自然指向就是对象a。this的指向在函数创建的时候是决定不了的,在调用的时候才能决定,谁调用的就指向谁。
总结
- 如果一个函数中有this,但是它没有被上一级的对象所调用,那么this指向的就是window。
- 如果一个函数中有this,这个函数有被上一级的对象所调用,那么this指向的就是上一级的对象。
- 如果一个函数中有this,这个函数中包含多个对象,尽管这个函数是被最外层的对象所调用,this指向的也只是它上一级的对象。
- 可以通过call,apply,bing强行改变this的指向。