1、在原型中使用this
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript">
window.οnlοad=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的一個方法!!!)