在JavaScript中使用timer樣本

來源:互聯網
上載者:User

複製代碼 代碼如下:
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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.