有下面这样一段代码,此时会弹出对话框,显示"i'm window id",说明了全局函数tt属于window对象,而全局变量id也属于window对象,它们之间就可以象普通对象之间那样通过this来进行访问。 var id = "i'm window id";
function tt()
{
alert(this.id);
}
tt();
下面是三种不同的监听绑定事件:
1 <div id="ss" onclick="tt();">tt</div>
2 document.getElementById("ss").onclick = function(){tt();}
3 document.getElementById("ss").onclick = tt;
在代码1和2中,tt函数是在onclick事件发生时执行,其上下文环境仍然属于window对象,所以此时不会得到正确的结果(div的id),而代码3中,tt函数作成为dom对象的一部分,此时就会正确弹出div的id值:"ss"。 通过以上原理,我们可以引申出一个既是函数又是类的混合体:
function ClassA(sColor)
{
this.color = sColor;
this.sayColor = function()
{
alert(this.color);
}
}
在作为全局函数使用的时候,子函数sayColor又可以作为独立的全局函数。直接在window的上下文环境中使用。


