36 sites, 11,103 entries and counting...     Get a free blog; Join a Weblog Network!
Top

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.

Comments

4 Responses to “Javascript static variables”

  1. Gustavo Muñoz :: :: June :: 2005 on June 3rd, 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 […]

  2. mike 18 boy cute gay on June 5th, 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/

  3. bontril on June 9th, 2006 12:17 am

    bontril…

    bontril Phrm889NetW0rkJP …

  4. amit on February 27th, 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

Got something to say?





Bottom