473,386 Members | 1,779 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

static variables?

Does JavaScript have "static" variables. That is, as in C (or local in
Perl)? How can I keep a variable in a JavaScript function that doesn't
change from call to call? It may not make sense in JavaScript; I'm not
sure when the variables are re-set, but I assume it's at each page full
reload. But, what if I want to validate a form, and force a user to
re-enter something I find invalid, but only do it the first 1 or 2
times. Then, I will let them out, so as not to lock them into a field.
Must I use standard global variables for this, or does JavaScript have
a static variable that doesn't involve object-oriented framework?
Thanks,
jab3

Mar 1 '06 #1
7 8028
jab3 said the following on 3/1/2006 2:21 AM:
Does JavaScript have "static" variables. That is, as in C (or local in Perl)?
No, it has no concept of static variables.
How can I keep a variable in a JavaScript function that doesn't
change from call to call? It may not make sense in JavaScript; I'm not
sure when the variables are re-set, but I assume it's at each page full
reload.
Depends on where the variable is defined when it is "reset".
But, what if I want to validate a form, and force a user to
re-enter something I find invalid, but only do it the first 1 or 2
times. Then, I will let them out, so as not to lock them into a field.


Use a global variable and every time they get it wrong, increment your
global counter. When it reaches the max tries, ignore it:

var counter = 0;

function validateForm(){
if (counter<3){
//validation code here.
}
}

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Mar 1 '06 #2
VK

jab3 wrote:
Does JavaScript have "static" variables. That is, as in C (or local in
Perl)?
'static' in JavaScript has rather C++ sense: "a single instance of
something shared among all instances of the given constructor".

If you're talking about Perl-like 'local' (thus "visible to the given
function and all functions called from that function") then this scope
doesn't exists in JavaScript - though it can be emulated. But you seem
do not need it for this particular task (?)
How can I keep a variable in a JavaScript function that doesn't
change from call to call?
By making such variable global or by making it a property of some
persistent object.
It may not make sense in JavaScript; I'm not
sure when the variables are re-set, but I assume it's at each page full
reload.
On full reload the whole global context is being re-initialized,
including any variables - global or local. To keep states between page
loads you need then either use cookies or the search part of URL, or
hidden form fields.
But, what if I want to validate a form, and force a user to
re-enter something I find invalid, but only do it the first 1 or 2
times. Then, I will let them out, so as not to lock them into a field.
Must I use standard global variables for this, or does JavaScript have
a static variable that doesn't involve object-oriented framework?


Unless there are some extras in your situations, I would go with a
global var.

Mar 1 '06 #3
VK

VK wrote:
Unless there are some extras in your situations, I would go with a
global var.


Just donged on me ! :-)
You must want a separate counter for each form filed, this is why all
these local issues. In such case you can add extra property to the form
element itself:

function validate(elm) {
// elm is a form element reference
if ('undefined' == elm.counter) {
elm.counter = 0;
}
else {
elm.counter++;
}
if (elm.counter <= 2) {
// be nasty
}
else {
// let it go
}
}

P.S. You are welcome to compact the above

Mar 1 '06 #4
VK wrote:
Unless there are some extras in your situations, I would go with a
global var.


Global vars should be avoided when possible (a 'best practice' I'll add to
my document).

You can achieve the effect of a "static variable" using closures as below.
The function should, of course, be expanded to be more useful than it is
written.

<html>
<head>
<title>Example</title>
<script type="text/javascript">
var validateField = (function(){
var count = 0;
return function(o) {
if (count++<2 && o.value=="") {
alert("Field cannot be empty!");
return false;
}
return true;
}
})();
</script>
</head>
<body>

<form action="/" method="get">
<input type="text" name="field" value="">
<input type="button" onClick="validateField(this.form.field)"
value="Validate">
</form>

</body>
</html>
--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Mar 1 '06 #5
"jab3" <ja*****@gmail.com> writes:
Does JavaScript have "static" variables. That is, as in C (or local in
Perl)? How can I keep a variable in a JavaScript function that doesn't
change from call to call?
Not directly, no.
It's not necessary either, since Javascript has block scoping and
closures, so you can create a variable that is only visible inside a
function without doing it inside the function:

var myFunc = (function(){
var myStaticVariable = 0;
return function myFunc() {
return myStaticVariable++;
}
})();

That's really all static variables are in C anyway: globally stored
variables with local scope.
It may not make sense in JavaScript; I'm not sure when the variables
are re-set, but I assume it's at each page full reload.
When you load a page, everything goes away. You must use cookies or
pass information in the URL to keep state from one page to the next.
But, what if I want to validate a form, and force a user to re-enter
something I find invalid, but only do it the first 1 or 2 times.


That sounds like state that should be kept somewhere, and not
necessarily hidden inside a function. It makes the function impossible
to reuse if it has state hardwired into it.

/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.'
Mar 1 '06 #6
On 01/03/2006 18:46, Lasse Reichstein Nielsen wrote:
[...] Javascript has block scoping and closures [...]


The latter certainly, but block scoping? Surely you mean function-local
variables?

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Mar 1 '06 #7
Michael Winter <m.******@blueyonder.co.uk> writes:
On 01/03/2006 18:46, Lasse Reichstein Nielsen wrote:
[...] Javascript has block scoping and closures [...]


The latter certainly, but block scoping? Surely you mean
function-local variables?


Indeed. I got carried away there :)

/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.'
Mar 1 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: James | last post by:
Hello Java NG, I not sure if this is the right NG for this type of question but if not please let me know which is, TIA Any way first off let me say I'm a student and this WAS last weeks lab,...
2
by: katekukku | last post by:
HI, Could anyone please tell me what are static variables and what exactly are there features. I am a little bit confused. Thank You
9
by: Bryan Parkoff | last post by:
I have noticed that C programmers put static keyword beside global variable and global functions in C source codes. I believe that it is not necessary and it is not the practice in C++. Static...
4
by: Dave | last post by:
I used the following class and .aspx code below to understand how static works on variables and methods taken from...
8
by: Simone Chiaretta | last post by:
I've a very strange behaveour related to a website we built: from times to times, something should happen on the server, and all static variables inside the web application, both defined inside aspx...
28
by: Dennis | last post by:
I have a function which is called from a loop many times. In that function, I use three variables as counters and for other purposes. I can either use DIM for declaring the variables or Static. ...
5
by: Jesper Schmidt | last post by:
When does CLR performs initialization of static variables in a class library? (1) when the class library is loaded (2) when a static variable is first referenced (3) when... It seems that...
9
by: CDMAPoster | last post by:
About a year ago there was a thread about the use of global variables in A97: http://groups.google.com/group/comp.databases.ms-access/browse_frm/thread/fedc837a5aeb6157 Best Practices by Kang...
55
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in...
16
by: RB | last post by:
Hi clever people :-) I've noticed a lot of people stating not to use static variables with ASP.NET, and, as I understand it, the reason is because the variable is shared across user sessions -...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.