In javascript if I need objects each to have an individual value of an attribute, I can just set it in the constructor, like so:
function A(x) {
this.a = x;
}
If I want a certain attribute to be shared among the objects, I can set it in the prototype of constructor function.
function B() {}
B.prototype.b = 'B0';
But what to do in in-between situation? Basically, I have an existing code where all the constructed objects inherit a property from a prototype, but now I need to divide them into several groups so all members of a group share an attribute.
Is there a way to specialize the constructor function B somehow?
B.prototype.bdoes NOT create a static property as you presume. It’s a bit more complicated than that, properties attached to a prototype share their value with other instances, until they overwrite that value, meaning that:The only way to have “real” static properties is to attach them to the constructor function itself:
instances of
Foowill have to access that value withFoo.bar2.So the answer to your question is to create “subclasses” (constructor functions that inherit their prototype from a base constructor function) for each group and attach a property per subclass, like this:
Warning:
Group1.prototype = new Base();is actually bad practice, I wrote a blog post about 3 types of inheritance just a few days ago which explains why:http://creynders.wordpress.com/2012/04/01/demiurge-3-types-of-javascript-inheritance-2/