Overriding functions from objects in JS list

I have a list, let’s say

var elements = List.<NormalElement>();

and I’m going through it, calling some function for each, let’s say

for (var c : NormalElement in elements)

Now let’s say that the NormalElement class has

virtual function Draw() : boolean
     Debug.Log("i'm normal!"); 
     return true;

and some SpecialElement class (which extends NormalElement) ALSO has

virtual function Draw() : boolean
     Debug.Log("i'm special!");
     return false;

My problem is that I seem to be unable to access the subclass’ Draw() function when I am getting at the object through that list. What would be the best way to restructure this so that I can call Draw() on the entire collection of elements, and each will use the appropriate Draw() call?

I was thinking you should use interfaces. Create an interface, IDrawable in this case, and maintain a list of all IDrawables.

So your interface could be

public interface IDrawable{

    void Draw();

and you’d then just implement that in each class that has the ability to draw:

public class NormalElement extends MonoBehaviour implements IDrawable{

    public void Draw(){/*implementation*/}

Doing this, you can have a List.< IDrawable >, which you can iterate through and call any function IDrawable declares. In this case, only Draw();.

The upside with this is you may now create classes that don’t have anything to do with NormalElement. If in the future, you find yourself in a need to add a class that draws a circle, you may do so by public class CircleDrawer extends MonoBehaviour implements IDrawable. The downside is that Unity’s GetComponent doesn’t work with interfaces, so you’ll have to create a custom solution. This answer describes one I use. You may not know explicitly which class you’re currently using, either.

Another alternative is to simply, for each element in the list, check if it’s a SpecialElement and downcast it. This will work nicely if you have one or two special cases, but will get ugly with more.

for(var obj in NormalElementList)
    if(typeof(obj) == typeof(SpecialElement))