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的一个方法!!!)