Copy Code code as follows:
function foo ()
{
}
SetInterval ("foo ()", 1000);
If you use OO technology, you can do this,
Copy Code code as follows:
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 ();
}
However, it does not work as you would imagine. The reason is that the setinterval () function does not recognize this variable. A workaround way to do this.
Copy Code code as follows:
function Another ()
{
var obj = NW myobj ();
SetInterval ("Obj.timer ()", 1000);
}
Obviously, it can work correctly, but if you're a perfectionist, you won't be satisfied with it. Fortunately, you can put this action in the constructor and change the form somewhat.
Copy Code code as follows:
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, by using a closure, it's okay. As for the reason, I want to give the reader to think for themselves.
Finally, give an example of a variety of test cases.
Copy Code code as follows:
<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>
<body>
<input type = "button" onclick = "onclick ()" VALUE = "click me" ></input>
</body>