Skip to content Skip to sidebar Skip to footer

Extending An Array Properly, Keeping The Instance Of Subclass

I've written a class trying to extend the native Javascript Array class with a custom class, let's call it MyClass. This is basically what it looks like: class MyClass extends Arra

Solution 1:

Why doesn't myInstance.first() instanceof MyClass return true?

Because first calls slice, and Array.prototype.slice does always return an Array. You will need to overwrite it with a method that wraps it in a MyClass again:

classMyClassextendsArray

  constructor: (obj) -> @push.apply @, obj

  slice: () -> newMyClasssuper
  splice: () -> newMyClasssuper
  concat: () -> newMyClasssuper
  filter: () -> newMyClasssuper
  map: () -> newMyClasssuper

  first: -> @slice0, 1

And notice that subclassing Array does not work.

Post a Comment for "Extending An Array Properly, Keeping The Instance Of Subclass"