Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Object problem

1 view
Skip to first unread message

Cylix

unread,
Jul 3, 2006, 12:37:40 AM7/3/06
to
This is my object:
###################################################
function msgList() {
this.t = 5000;
this.timer = timer;
}

// ---------------------------------------
// ::: Methods for msgList
// ---------------------------------------
function timer() {
alert(this.t);
setTimeout('this.timer();', this.t);
}

var lst = new msgList;
lst.timer();
##################################################

5000 is shown when the first time, then this.t become undefine.
I thing the meaning of "this" is not the same one at the first calling,

any one can explain this to me??

actually, I wanna to show the time const which is attribute of the
object at the function.
How can I do this?

Thing you.

Lasse Reichstein Nielsen

unread,
Jul 3, 2006, 2:11:24 AM7/3/06
to
"Cylix" <cyli...@gmail.com> writes:

> function timer() {
> alert(this.t);
> setTimeout('this.timer();', this.t);
> }

> any one can explain this to me??

If the first argument to setTimeout (or setInterval) is a string,
the code is parsed and executed in the global scope and with "this"
referring to the global object.

If you change the first argument to a function expression, then that
function is called as a function, not as a method, so "this" again
refers to the global object, but the function closure retains its
scope chain.

This can be used to your advantage:

function timer() {
alert(this.t);
var self = this;
setTimeout(function(){self.timer();}, this.t);
}

This causes the timeout to call a function that knows the current
"this" object (by the name "self"), and calls the "timer" method
on it as a method.

/L
--
Lasse Reichstein Nielsen - l...@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'

0 new messages