I’ve just stumbled upon what I consider strange behavior which might well just be my misunderstanding of how javascript inheritance works…
I’m using OpenLayers, which is based on prototypejs to create classes and subclasses. I expected that fields declared in the super class would become separate objects in each instantiation of the class or subclasses. This does not seem to be the case however, as you can see in the below example.
The super class MySuperClass defines the field collection however even though I construct multiple instances of this class, and via subclasses the field collection seems to be shared, as if it is static?
Why is it so, and how do I safely create an instance variable in the definition of a super class?
<script type="text/javascript" src="http://openlayers.org/dev/OpenLayers.js"></script>
<script type="text/javascript">
OpenLayers.MySuperClass = OpenLayers.Class(
{
collection: [],
initialize: function(options)
{
OpenLayers.Util.extend(this, options);
},
addItem: function(listener)
{
this.collection.push(listener);
}
});
OpenLayers.MySubClassOne = OpenLayers.Class(OpenLayers.MySuperClass,
{
initialize: function(options)
{
OpenLayers.MySuperClass.prototype.initialize.apply(this, arguments);
}
});
OpenLayers.MySubClassTwo = OpenLayers.Class(OpenLayers.MySuperClass,
{
initialize: function(options)
{
OpenLayers.MySuperClass.prototype.initialize.apply(this, arguments);
}
});
var instanceOne = new OpenLayers.MySubClassOne();
instanceOne.addItem("one");
var instanceTwo = new OpenLayers.MySubClassTwo();
instanceTwo.addItem("two");
var instanceSuperOne = new OpenLayers.MySuperClass();
instanceSuperOne.addItem("three");
var instanceSuperTwo = new OpenLayers.MySuperClass();
instanceSuperTwo.addItem("four");
alert(instanceOne.collection);
alert(instanceTwo.collection);
alert(instanceSuperOne.collection);
alert(instanceSuperTwo.collection);
</script>
I’m not really sure about this one, but I guess it is because you initialize the
collectionfield in the class. Notice that the class is just an object, not a function. If you want it to be on instance level, you should initialize it in the constructor, in case of OpenLayers it’sinitialize. I observed similar behaviour in jQuery UI and comming from an object-oriented language, I found this kind of confusing.