js中setTimeout用在对象内部时,如何回调this.xxx()

在JavaScript中使用timer很容易,

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的例子。


<html>
<head>
<title>
Hello Timer
</title>
<script language = "JScript">

/*
* There are 3 classes.
*
* 1. timer can run and result is ok
* 2. timer can run and result is wrong
* 3. timer can not run
*
*/

function Obj()
{
    function foo()
    {
        alert( this.timer );
    }
   
    this.timer = foo;
   
    //
    var me = this;
    var f = function() { me.timer(); };
    var f2 = function() { this.timer(); };
   
    // 1st class
    //setInterval( f, 1000 );
    // 3rd class
    //setInterval( f2, 1000 );
    // 2nd class
    //setInterval( me.timer, 1000 );
    //setInterval( this.timer, 1000 );
    //setInterval( foo, 1000 );
    // 3rd class
    //setInterval( "this.timer()", 1000 );
    //setInterval( "me.timer()", 1000 );
    //setInterval( "foo()", 1000 );
}

var o = null;

function OnClick()
{
    o = new Obj();
    // 1st class
    //setInterval( "o.timer()", 1000 );
    setInterval( function() { o.timer(); }, 1000 );
    // 2nd class
    //setInterval( o.timer, 1000 );
}

</script>
</head>
<body>
<input type = "button" onclick = "OnClick()" value = "Click me"></input>
</body>
</html>


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/Viper/archive/2005/12/28/563868.aspx

你可能感兴趣的:(JavaScript,timer,工作,function,Class,button)