第一件事情.
this 指鐘是JavaScript語言中的一個特殊指鐘,他在代碼運行時,指向調用this語句的當前對象.
如果是事件綁定函數,則指向被綁定的元素本身.
<script type="text/javascript">
//by Go_Rush(阿舜) from http://ashun.cnblogs.com/
alert(this===window) //true 直
接調用的時候,指向window本身
var gorush={
f:function(){
alert(this===gorush) //true
}
}
gorush.f() //指向 gorush對象
document.onclick=function(){
alert(this===document) //true ,指向 document
}
/*
element.onclick=function(){
alert(this===element) //true
}
*/
</script>
特別要值得注意的是,當多個對象嵌套的時候, this 是指向最近調用它的那個對象的
obj1={
obj2:{
f:function(){
alert(this===obj1.obj2) //這里 this 并不是指向 obj1的哦。
}
}
}
obj1.obj2.f()
再舉一個非常容易出錯的例子, 點這里看相關鏈接
<script type="text/javascript">
//by Go_Rush from http://ashun.cnblogs.com/
//以下gorush1中 this的用法是錯誤的,這個錯誤10個程序員6個犯
var gorush1={
showMsg:function(){alert("hello,world")},
doAjax:function(){
new Ajax.Request("index.php",{onSuccess:function(){
this.showMsg()
}})
}
}
//gorush2中的才是對的
var gorush2={
showMsg:function(){alert("hello,world")},
doAjax:function(){
var self=this; //備份 gorush2對象
new Ajax.Request("index.php",{onSuccess:function(){
self.showMsg()
}})
}
}
</script>
第二件事情:
閑話不多說,先上碟小菜.
<script type="text/javascript">