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) {;

displayBar: function() {
alert (;

var foo = new Foo();

// Alert displays 1,2

// Destoy the object
foo = null;

// Create a new one…
var x = new Foo();

// What does this display?

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. = 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();
    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 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

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