私が強くお勧めする OpenLayers.Feature.Vector クラスを拡張する場合は、OpenLayers.Class オブジェクトを使用する必要があります。
SpecialRegion = OpenLayers.Class(OpenLayers.Feature.Vector, {
customAttribute: 'value',
/**
* OpenLayers Constructor
*/
initialize: function(bounds, options) {
// Call the super constructor, you will have to define the variables geometry, attributes and style
OpenLayers.Feature.Vector.prototype.initialize.apply(this, {geometry, attributes, style});
this.customAttribute = 'new value';
},
// Each instance will share this method. It's clean and efficient
customMethod: function(param) {
...
}
});
インスタンス化
var myVector = new SpecialRegion(bounds, options);
myVector.customMethod(param);
var val = myVector.customAttribute;
独自のクラスを定義せずに、単一のインスタンスに特別なメソッドや属性を定義するだけの場合:
注:これを頻繁に行うと、アプリケーションが非常に面倒になる可能性があります。上記の解決策をお勧めします。
function customMethod2 = function(param) {
...
};
function SpecialRegion(bounds, options) {
// Call the constructor, you will have to define the variables geometry, attributes and style
var vector = new OpenLayers.Feature.Vector(geometry, attributes, style);
vector.customAttribute = 'new value';
// Each instance created with SpecialRegion will have their own copy of this method, the code is cleaner but it's memory inefficient
vector.customMethod = function(param) {
...
};
// Each instance share the same copy of this method (defined on top), the code is harder to read/maintain but it's more memory efficient
vector.customMethod2 = customMethod2;
return vector;
};
インスタンス化
var myVector = SpecialRegion(bounds, options);
// Don't use the keyword 'new' here, SpecialRegion is a function, not a proper class.
myVector.customMethod(param);
myVector.customMethod2(param);
var val = myVector.customAttribute;