this的指向
作者:互联网
1.this指向它的调用对象
function getA(){ var a = 1; console.log(this); //window console.log(this.a); //undefined } getA(); //等价于window.getA() var getA={ a:"1", fn:function(){ console.log(this.a) //1 } } getA.fn(); //此时this指向对向getA var getA={ a:1, fn:function(){ console.log(this.a) //1 } } window.getA.fn(); //此时this仍然指向getA(),this只会指向他的上一级 var getA={ a:1, b:{ a:5, fn:function(){ console.log(this.a); //5 } } } getA.b.fn(); var getA={ a:1, b:{ a:5, fn:function(){ console.log(this.a); //undefined } } } var c = getA.b.fn; c(); //fn赋值给变量C时没有执行,所以最终指向是window 2.new会改变this的指向 function getA(){ this.a = 1; } var b = new getA(); console.log(b.a); //1,new等于将getA()复制了一份到对象B中 function getA(){ this.a = 1; return{}; } var b = new getA(); console.log(b.a); //undefiend function getA(){ this.a = 1; return function(){}; } var b = new getA(); console.log(b.a); //undefiend function getA(){ this.a = 1; return 1; } var b = new getA(); console.log(b.a); //1 function getA(){ this.a = 1; return undefined; } var b = new getA(); console.log(b.a); //1 function getA(){ this.a = 1; return null; } var b = new getA(); console.log(b.a); //1 3.call,apply会改变this指向 var getA={ a:1, fn:function(){ console.log(this.a); } } var b = getA.fn; b.call(getA); call可以添加多个参数 var getA={ a:1, fn:function(c,d){ console.log(this.a); //1 console.log(c+d); //7 } } var b = getA.fn; b.call(getA,3,4); apply与call类似,但是apply的第二个参数必须是数组 var getA={ a:1, fn:function(){ console.log(this.a); //1 } } var b = getA.fn; b.apply(getA); var getA={ a:1, fn:function(c,d){ console.log(this.a); //1 console.log(c+d); //7 } } var b = getA.fn; b.call(getA,[3,4]); 如果call和apply的第一个参数写的是null,则指向window标签:function,console,log,指向,getA,var,fn 来源: https://www.cnblogs.com/wha000/p/11357312.html