Our website would like to use cookies to store information on your computer. You may delete and block all cookies from this site, but parts of the site will not work as a result. Find out more about how we use cookies.

Login or Register

Powered by
Powered by Novacaster
 
Javascript: don't move!
by Bruce Ure at 15:49 22/03/05 (Forum::Technical Advice::General)
Please someone tell me Javascript isn't missing the concept of static variables.
I've trawled the web for ages and can't find anything definitive, it really is beginning to look as if it can't be done.

:bu:

<< View comments Iiyama monitors, quickasyoulik... >>
View Comments (Threaded Mode) Printer Version
Javascript: don't move! Bruce Ure - 15:49 22/03/05
Re: Javascript: don't move! Simon - 16:13 22/03/05
What's wrong with

var Foo = 'hello';
alert(Foo);

then?
--
simon

Re: Javascript: don't move! Bruce Ure - 16:19 22/03/05
Nah mate. I want:

function bum() {
static var bumCount = 0;
bumCount++;
alert('bum() has run ' + bumCount + ' times);
}

To get round it I can define bumCount with wider scope but it's a bit messy.

If Javascript doesn't support statics there must be a good reason..

Re: Javascript: don't move! Simon - 16:49 22/03/05
By default variables are page-scoped (I believe), so if you pull in two .js files and define a var at the top of one then it's available to the other.
--
simon
Re: Javascript: don't move! Simon - 17:02 22/03/05
In Perl, (courtesy of Hugo explaining what you mean by static variable :-)) you could have:


{
my $bumCount = 0;
   sub bum {
      $bumCount++;
      warn "Bum has run $bumCount times\n";
   }
}

... ie you create a 'bare block' {} around the subroutine to constrain the scope of $bumCount and ensure that it only gets initialised to 0 the first time the program is run, not for every invocation of the subroutine.
--
simon