By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,623 Members | 1,773 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,623 IT Pros & Developers. It's quick & easy.

Object problem

P: n/a
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.

Jul 3 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
"Cylix" <cy*******@gmail.comwrites:
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 - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 3 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.