function foo()
{
}
setInterval( "foo()", 1000 );
如果使用OO的技术,可以这样,
// constructor
function MyObj
{
function foo()
{
alert( this.data );
}
this.timer = foo;
this.data = "Hello";
setInterval( "this.timer()", 1000 );
}
function Another()
{
// create timer when create object
var obj = new MyObj();
}
但是,它并不能像你想像的那样工作。原因在于setInterval()这个函数并不能识别this这个变量。一个workaround 的方法可以这样。
function Another()
{
var obj = nw MyObj();
setInterval( “obj.timer()”, 1000 );
}
显然,它可以正确工作,但如果你是一个完美主义者,你就不会对它满意。幸运的是,可以将这个动作放到构造函数中去,形式上有点变化。
// constructor
function MyObj
{
function foo()
{
alert( this.data );
}
this.timer = foo;
this.data = "Hello";
var self = this;
setInterval( function() { self.timer(); }, 1000 );
}
function Another()
{
var obj = new MyObj();
}
OK, 通过使用一个闭包,就可以了。至于其中的原因,我想给读者自己去思考。
最后,给一个各种测试case的例子。
Hello Timer
<script language="JScript"> <br><br>/* <BR>* There are 3 classes. <BR>* <BR>* 1. timer can run and result is ok <BR>* 2. timer can run and result is wrong <BR>* 3. timer can not run <BR>* <BR>*/ <br><br>function Obj() <BR>{ <BR>function foo() <BR>{ <BR>alert( this.timer ); <BR>} <br><br>this.timer = foo; <br><br>// <BR>var me = this; <BR>var f = function() { me.timer(); }; <BR>var f2 = function() { this.timer(); }; <br><br>// 1st class <BR>//setInterval( f, 1000 ); <BR>// 3rd class <BR>//setInterval( f2, 1000 ); <BR>// 2nd class <BR>//setInterval( me.timer, 1000 ); <BR>//setInterval( this.timer, 1000 ); <BR>//setInterval( foo, 1000 ); <BR>// 3rd class <BR>//setInterval( "this.timer()", 1000 ); <BR>//setInterval( "me.timer()", 1000 ); <BR>//setInterval( "foo()", 1000 ); <BR>} <br><br>var o = null; <br><br>function OnClick() <BR>{ <BR>o = new Obj(); <BR>// 1st class <BR>//setInterval( "o.timer()", 1000 ); <BR>setInterval( function() { o.timer(); }, 1000 ); <BR>// 2nd class <BR>//setInterval( o.timer, 1000 ); <BR>} <br><br></script>










