如下代码:
<script type="text/javascript">
function show()
{
window.alert(this.info);
}
function MyInformation(mycity,myuniversity,myyear)
{
this.city=mycity;
this.university=myuniversity;
this.year=myyear;
this.info="毕业于"+this.city+this.university+":"+this.year+"年";
this.show=show;
}
MI=new MyInformation("成都","电子科技大学","1999");
</script>
<form>
<input type="button" value="aboutme" onclick="JavaScript:MI.show()" />
</form>
这是一般js教材上的一段例子
下面的那个MyInformation函数是一个类的声明,也就是说MyInformation是一个类的构造器,而它里面有一句this.show=show;
这一句的意思是这个类中有一个show方法(this.show),所谓方法就是类特有的一个函数,所以在show这个函数,其实是MyInformation类的一个方法,而show里面的this,当然指的是MyInformation这个类本身,而不是show.
这个例子,这样写对于初学者可能不是很好理解,
实际应该把function show(){...}这个函数写到MyInformation的里面
也就是类似于:
function MyInformation(){
this.xxx=aaa;
this.yyy=bbb;
....
this.show=function(){
alert(this.info);
}
}
当然我们还可以通过prototype原型构造器来构造这个方法,形如:
function MyInformation(){
this.xxx=aaa;
this.yyy=bbb;
....
}
MyInformation.prototype.show=function(){
alert(this.info);
}
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()
}})
}
}
this总是指向调用该方法的对象,如:
var oCar = new object;
oCar.color = "red";
oCar.showColor = function()
{
alert(this.color);//output red
}
这里关键字this用在对象的showColor 方法里,this等于oCar
在市里花对象的时候,总不能确定开发者会使用什么样的变量名,用this即可在任意多个地方重用一个函数
如果不用对象或this引用变量,则会把它看成全局变量或局部变量