Skip navigation
Currently Being Moderated

How to extend system classes

Apr 28, 2012 12:30 AM

Hi,

 

just an example: I am using lots of arrays in my code, and so repeat the stanza

somearray[somearray.length-1]

all over the place.

Now, I could do something like

 

public dynamic class MyArray extends Array

{    public function get last():*

     {    return this[this.length-1];

     }

}

 

and replace all instances of new Array() by new MyArray().

This would allow to use

somearray.last

 

However, this would lose the shortcut [], and the "last" accessor would not be available on arrays set up by system code (say as part of data

collections)

There are similar examples for static functions that I would like to add to some classes. I could, of course, collect them into a class MathUtil or 'GeomUtil,

but I would prefer to relate them to, say Point or Vector3D

 

I have seen "prototype chain" etc mentioned, would that help?

 
Replies
  • kglad
    72,213 posts
    Jul 21, 2002
    Currently Being Moderated
    Apr 28, 2012 12:12 PM   in reply to birnerseff

    create a static method:

     

    package {

       

        public class A {

     

            public static function last(a:Array):*{

                return a[a.length-1];

            }

        }

    }

     
    |
    Mark as:
  • Currently Being Moderated
    Apr 29, 2012 4:27 AM   in reply to birnerseff

    >>However, this would lose the shortcut [], and the "last" accessor would not be available on arrays set up by system code (say as part of data collections)

     

    I would say not an issue to both of those. When do you really use []? I never use it... and who cares about arrays set up by system code? This solves your issue... but while I don't see your first solution as a problem, I would use kglads way - and do actually. I have an array utilities class and make use of it exactly like that: A.last(myarray) and I do think it makes the code more readable as well. Just my .02

     
    |
    Mark as:

More Like This

  • Retrieving data ...

Bookmarked By (0)

Answers + Points = Status

  • 10 points awarded for Correct Answers
  • 5 points awarded for Helpful Answers
  • 10,000+ points
  • 1,001-10,000 points
  • 501-1,000 points
  • 5-500 points