"Inherit" from Array()
In javascript it's possible to create a type of Inheratence via prototyping. You can Expand the native objects too. But it's not possible to inherit from say the Array() object, without using a factory.
function NewArray(){};
NewArray.prototype = new Array();
NewArray.prototype.constructor = NewArray;
NewArray.prototype.Add = function(obj)
{
// Do some special login with the object
// before Adding it to the Array
this[this.length] = obj;
}
function test()
{
var oNewArray = new NewArray();
oNewArray.Add( "First Item" )
oNewArray.Add( "Second Item" )
alert(oNewArray[0]);
}
Test this code As you can see oNewArray[0] alerting the second item not the first. This is because the length property is no longer incrementing.
Using a Factory. One way to get round this is to create the instance of the Array before adding functionality to it.
function test2()
{
var oMyArray = (new MyArray()).instanceOf();
oMyArray.Add( "First Item" )
oMyArray.Add( "Second Item" )
alert( oMyArray[0] );
alert( oMyArray[1] );
alert( oMyArray.length );
}
function MyArray()
{
this.instanceOf = function ()
{
var self = new Array();
self.Add = function ( obj)
{
if( obj )
{
this[this.length] = obj;
}
}
return self;
}
}
Test this code As you can see now it's possible to access all of the item and the .length property is is correct making it possible to loop the new MyArray() object.
I know I could have manually incremented the .length property of the object in the Add method but I wasn't too sure of what else was not functioning correctly