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:

class MyClass extends Array

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

  slice: () -> new MyClass super
  splice: () -> new MyClass super
  concat: () -> new MyClass super
  filter: () -> new MyClass super
  map: () -> new MyClass super

  first: -> @slice 0, 1

And notice that subclassing Array does not work.


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