[JavaScript]OO的Timer

在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>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值