<HTML>
<HEAD>
<TITLE> New Document </TITLE>
</HEAD>
<BODY>
<script>
var tm = "";
function timer()
{
this.year='2006';
this.display = display;
this.f = f;
tm=this.year;
}function display()
{
f();
}
function f()
{ alert(tm);
}
</script>
<script>
var t = new timer ();
t.display();
</script></BODY>
</HTML>
<HEAD>
<TITLE> New Document </TITLE>
</HEAD>
<BODY>
<script>
var tm = "";
function timer()
{
this.year='2006';
this.display = display;
this.f = f;
tm=this.year;
}function display()
{
f();
}
function f()
{ alert(tm);
}
</script>
<script>
var t = new timer ();
t.display();
</script></BODY>
</HTML>
{
f(); //在这个函数里再调用 f() 的话,那f()里的 this 将不再指向 timer 而是window
}
function f()
{
alert(this.year);
}你设置一个变量试试看:
var year = "this is window.year";
function display()
{
f();
}
function f()
{
alert(this.year);
}
为什么 timer 里的this不是指向window,而f()里面的this 却是指向 window呢?
是不是因为用 var t = new timer (); 创建了一个timer对象,这时timer()里面的this就是指向对象t了?
而没有创建f()的对象,这时f()里面的this就默认的指向window?