Sunday, April 22, 2007

Note on JavaScript prototypes and object variables

This makes complete sense, once you think about it, but I didn't at first and it bit me.

>>> function Obj() { }
>>> Obj.prototype.position = { "x" : 0 , "y" : 0 };
Object x=0 y=0
>>> var a = new Obj();
>>> var b = new Obj();
>>> a.position.x = 10;
10
>>> b.position.x
10

This Firebug console output shows writing a simple object, Obj, and setting a prototype variable position to an object literal having two member variables, x and y, both initially set to 0. Since object instances simply reference their prototype variables when set to objects (Array, Object, Function, etc.), updating instance a's x position will update instance b's x position as well.

In order to get around this, while still setting aside a spot for the position variable in the Obj prototype, assign the value in the constructor like this:

>>> function Obj() { this.position = { "x" : 0 , "y" : 0 }; }
>>> Obj.prototype.position = null;
null
>>> var a = new Obj();
>>> var b = new Obj();
>>> a.position.x = 10;
10
>>> b.position.x
0

It doesn't look as nice, and requires that you call the parent constructor when you extend the object (always a fun process with OO JavaScript), but it works much better this way.

Labels: ,

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home