Javascript static variables

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.

6 Responses to Javascript static variables
  1. hoyu
    April 9, 2010 | 1:59 pm

    Here is a easier way,
    Foo.var1 =0
    Foo.var2 =0

  2. hoyu
    April 9, 2010 | 1:47 pm

    My way of setup static variables would be:

    function Foo(){};
    Foo.prototype = { staticvar:{var1:1,var2:2}}

    if you do :
    var a = new Foo();
    var b = new Foo();
    a.staticvar.var1++;
    b.staticvar.var1’s value will change to 2 as well

  3. amit
    February 27, 2008 | 12:27 am

    hi would like to know that how dafine a static variable in javascript : that i can use it further in recalling the function

  4. bontril
    June 9, 2006 | 12:17 am

    bontril…

    bontril Phrm889NetW0rkJP …

  5. mike 18 boy cute gay
    June 5, 2006 | 2:48 pm

    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/

  6. Gustavo Muñoz :: :: June :: 2005
    June 3, 2005 | 1:58 am

    […] 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 […]