js中的this

1、普通函数
function test(){
		console.info(this);
		console.info(this.t);
	}
	
	test();//此时的this指向的是window,所以this.t=1;


2、函数被当成方法去调用时


var obj = {
		t:2,
		test:function(){
			console.info(this);
			console.info(this.t);
		}
	}
	
	obj.test();
	//  this.t --> 2
	//所以,当函数作为方法被调用的时候,this的指向会发生改变

3、作为构造函数,所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象。


var t1 = 1;
	
	function T2(){
		console.info(this);
		this.t1 = 3;
	}
	
	T2();
	alert(t1);// this指向window, this.t1 = 3 因为this指向window,所以全局的t1就会被改变,t1=3
	
	var tt = new T2();//此时,函数T2的this就会绑定到新建的对象上,所以this.t1也就相当于给对象tt添加了一个属性
	alert(tt.t1);//this指向tt,console.info(this)输出T2{},并且alert弹出3;
	
	//所以当作为构造函数时,this就指这个新对象。


原文地址:https://www.cnblogs.com/Iqiaoxun/p/5350606.html