Javascript static variables
June 2, 2005
Something I find strange about Javascript;
[code lang=”javascript”]
function Foo(){};
Foo.prototype = {
bar: [], // or ‘new Array()’ or ‘new Object()’
set: function(val) {
this.bar.push(val);
},
displayBar: function() {
alert (this.bar);
}
}
var foo = new Foo();
foo.set(1);
foo.set(2);
// Alert displays 1,2
foo.displayBar();
// Destoy the object
foo = null;
// Create a new one…
var x = new Foo();
// What does this display?
x.displayBar();
[/code]
By declaring the bar property to be an Array, it seems to make it static to values assigned to the array are in effect updating the class definition - later objects inherit those values. The same works for Objects and both Moz and IE behave the same way, so this would seem to be a feature. The only way to really free the memory is to modify the prototype e.g. Foo.prototype.bar = null;
Anyway haven’t seen it discussed before before - perhaps a useful feature or otherwise a path to eat up memory and forget to free it.





[…] ogy I found a question about an apparently strange behavior in JavaScript on the AjaxBlog. But the behavior that is posted there is the expected one because h […]
Houston always was Clemens’ most logical choice. He can stay home and follow his own program, remain in the same organization as his son, Class A third baseman Koby Clemens http://mike-18.blogspot.com/
bontril…
bontril Phrm889NetW0rkJP …
hi would like to know that how dafine a static variable in javascript : that i can use it further in recalling the function