If you are using OOP, you are familiar with initializing class members in the head of the source:
/** * Pseudocode */ class Foo { int i = 0; Array bar = new Array(); }
However, if you are using Javascript’s prototypying, assigning objects to class (prototype) members will result in static instance variables.
Example:
function Foo(){} Foo.prototype.i = 0;<br /> Foo.prototype.bar = new Array();
What happens here? If you create an object of the type Foo
, the prototype member bar
will hold a reference to the object (in this case an object of the type Array
) that was created and assigned before an instance of Foo
was created using new Foo()
. Thus, any objects of the type Foo
and their instance variable bar
will point directly to this object. Changes that are being made to bar
using an instance of Foo
will be visible to all instances of Foo
.
Example:
function Foo(){} Foo.prototype.i = 0; Foo.prototype.bar = new Array(0, 1); var foo1 = new Foo(); var foo2 = new Foo(); var foo3 = new Foo(); // setting value of foo1.bar at index 0 to 1 foo1.bar[0] = 1; alert(foo2.bar[0]); // alerts 1 instead of 0 alert(foo3.bar[0]); // alerts 1 instead of 0
You should avoid assigning objects to class members directly and instead call a method after instantiating to initiliaze members:
function Foo(){} Foo.prototype.i = 0; Foo.prototype.bar = null; Foo.prototype.init = function() { this.bar = new Array(0, 1); } var foo1 = new Foo(); foo1.init(); var foo2 = new Foo(); foo2.init(); var foo3 = new Foo(); foo3.init(); // setting value of foo1.bar at index 0 to 1 foo1.bar[0] = 1; alert(foo2.bar[0]); // alerts 0 alert(foo3.bar[0]); // alerts 0