I’m having a bit of trouble trying to get class variables to work in javascript.
I thought that I understood the prototype inheritance model, but obviously not. I assumed that since prototypes will be shared between objects then so will their variables.
This is why this bit of code confuses me.
What is the correct way to implement class variables?
function classA() {}; classA.prototype.shared = 0; a = new classA; //print both values to make sure that they are the same classA.prototype.shared; a.shared; //increment class variable classA.prototype.shared++; //Verify that they are each 1 (Works) classA.prototype.shared; a.shared; //now increment the other reference a.shared++; //Verify that they are each 2 (Doesn't Work) classA.prototype.shared; a.shared;
UPDATE: So it seems that everyone is confirming the fact that by incrementing the instance’s variable we don’t affect the prototype. This is fine, this is what I have documented in my example, but doesn’t this seem like an error in the design of the language? Why would this behavior be desirable? I find it weird that when the instance’s var is undefined we follow the hidden link to the prototype where we get the value of the var, but we copy it into the instance object.
I also understand that this isn’t java/c++/ruby/python, it’s a different language. I’m just curious as to why this behavior might be good.
They are, but this:
is not doing what you think it’s doing. It’s in fact (approximately) sugar syntax for:
(the -1 being to return the pre-increment value, not that you’re actually using the retrun value, but still.)
So this is actually doing an assigment to a.shared. When you assign to an instance member you are always writing to that instance’s own members, not touching any members of any of its prototypes. It’s the same as saying:
So your new a.shared hides the prototype.shared without altering it. Other instances of classA would continue to show the prototype’s value 1. If you deleted a.shared you would once again be able to see the prototype’s variable that was hidden behind it.