Static Variable for a Function?
Stretch65
Posts: 163
Hi,
I understand it's possible to create static variables in Javascript. Because functions are considered to be objects, it's possible to have something like this:
(function() { function doSomething(param) { if (doSomething.x == undefined) doSomething.x = 1; // this value is retained between calls }; doSomething.x = undefined; })()
Now, I'm trying to setup my own library of functions, and I'm told that it's best to define them in a separate namespace instead of putting them in the global namespace.
So for the above example, I'm doing the following (which uses Javascript's 'other' syntax where you define first the property and then the value):
var MyLibrary = { stuff : true, stuff2 : "hello", doSomething : function(param) { if (doSomething.x == undefined) { doSomething.x = 1; // this value is retained between calls } }, doSomething.x : undefined // this doesn't work - why??};
The trouble with this 'other' syntax is I can't figure out how to declare the static variable. Does anyone know how?
Comments
The variable doSomething.x isn't accessible until you have finished defining the object MyLibrary. This works:
Thanks. Javascript isn't exactly my favourite language :)
Not mine eiither! I'm baffled by it's popularity outside of web browsers.
ECMAscript do have some percuilar things,my favourite traps is still
function stupid(a,b) {
c=a+b;
printf(c);
}
a = 1;
b = someObjectArray[someindex].somemember;
stupid(a,b);
result >> 11
Really? Lol .. Now I hate this language even more.