日期:2014-05-16  浏览次数:20373 次

javascript---遇到关于this的相关问题(解决this)(持续更新中...)

1、在原型中使用this

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script type="text/javascript">
	window.onload=function  () {
		function a(){ 

			this.name="a"; 
			this.sex="男"; 
			this.num=0; 
		} 
		a.prototype.count=function(){ 
			this.num+=1; 
			alert(this.num); 
			if(this.num>10){return;} 
			//下面用四种方法测试,一个一个轮流测试。 
			//setTimeout("this.count()",1000);//A:当下面的x.count()调用时会发生错误:对象不支持此属性或方法。 
			//setTimeout("count()",1000);//B:错误显示:缺少对象 
			//setTimeout(count,1000);//C:错误显示:'count'未定义 
			//下面是第四种 
			var self=this; 
			setTimeout(function(){self.count();},1000);//D:正确 

		} 
		var x=new a(); 
		x.count(); 
	}
		

	</script>
</head>
<body>
	
</body>
</html>

错误分析:
A:中的this其实指是window对象,并不是指当前实例对象
B:和C:中的count()和count其实指的是单独的一个名为count()的函数,但也可以是window.count(),因为window.count()可以省略为count()

D:将变量self指向当前实例对象,这样js解析引擎就不会混肴this指的是谁了。 

另外:setTimeout()传入this的时候,当然指的是它所属的当前对象window了(因为setTimeout()是window的一个方法!!!)