日期:2014-05-16 浏览次数:20488 次
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>D:将变量self指向当前实例对象,这样js解析引擎就不会混肴this指的是谁了。
另外:setTimeout()传入this的时候,当然指的是它所属的当前对象window了(因为setTimeout()是window的一个方法!!!)