[Javascript] custom extension of Array object

liorean liorean at gmail.com
Thu Apr 14 12:22:42 CDT 2005


On 4/14/05, james <james at southspace.org> wrote:
> ok.. what I am wanting to do it this, I want to create a custom object
> which inherits all the methods of the Array object, but I don't want to
> alter the normal Array objects.

Like this?

    function CustomArray(){
    }
    CustomArray.prototype=new Array;
    
    var
        ca=new CustomArray;
    ca.push('test');
    ca.push('test');
    ca.push('test');
    alert(ca); // => test,test,test
 
> does this make sense?, the way I see it is that I make my custom object a
> 'subclass' of the Array object.

Doing exactly what you ask for is easy enough. Doing it so that the
lenght property is changed when you add properties with a positive
numerical identifier and so that the actual properties are cut off at
the given point when you change the length property, that can only be
achieved in engines that expose getter and setter interfaces.

> I would gratefully receive any advice, even if it was to tell me what I am
> trying to do is stupid!

Maybe you're addressing this in the wrong way, though. Is there a
compelling reason for you to use a custom object and inheritance
rather than using an array to which you have added the custom
properties? Something like this, if you want to make it a function:

    function CustomiseArray(arr){
        if(typeof arr=='undefined'||arr.constructor!=Array)
            arr=[];
        arr.customMethod=function(){};
        arr.customProperty='bite me!';
        return arr;
    }

    var
        ca=CustomiseArray();
-- 
David "liorean" Andersson
<uri:http://liorean.web-graphics.com/>



More information about the Javascript mailing list