我刚刚偶然发现了我认为奇怪的行为,这很可能只是我对 javascript 继承如何工作的误解......
我正在使用 OpenLayers,它基于prototypejs 来创建类和子类。我希望在超类中声明的字段将在类或子类的每个实例中成为单独的对象。然而,情况似乎并非如此,正如您在下面的示例中看到的那样。
超类MySuperClass
定义了该字段,collection
但是即使我构造了此类的多个实例,并且通过子类该字段collection
似乎是共享的,就好像它是static
?
为什么会这样,如何在超类的定义中安全地创建实例变量?
<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>