面向对象3-this的用法

1.当有定时器时 this会指向window  

<script type="text/javascript">
		function Aaa(){
			var _this=this;  //_this表示Aaa
			this.a=12;
			
			setInterval(function(){
//				console.log(this)  //this表示window
				_this.show();
			},1000)
		}
		Aaa.prototype.show=function(){
			console.log(this.a)
		}
		var obj=new Aaa();
//		obj.show()
	</script>

2.当有事件时,this会指向事件对象

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8" />
	<title>Document</title>
</head>
<body>
	
	<script type="text/javascript">
		function Bbb(){
//			console.log(this)   //this 这个表示 Bbb
			var _this=this;
			this.b=5;
//			document.getElementById("btn").onclick=this.show  //这里的this表示 input
			document.getElementById("btn").onclick=function(){
				_this.show()
			}
		}
		Bbb.prototype.show=function(){
			console.log(this.b)  /*this 表示*/
		}
		window.onload=function(){
			  new Bbb();
		}
	
	</script>
	
	<input type="button" name="" id="btn" value="按钮" />
</body>
</html>

  

原文地址:https://www.cnblogs.com/diyxiaoshitou/p/4149134.html