Question

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 Array

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

  first: -> @slice 0, 1

Instantiating the class is no problem. Running this in the console:

var myInstance = new MyClass(["1", "2"])
> ["1", "2"]
myInstance instanceof MyClass
> true
myInstance instanceof Array
> true

works as exptected.

The problem is that if I run:

myInstance.first()
> ["1"] // as expected
myInstance.first() instanceof MyClass
> false // not expected
myInstance.first() instanceof Array
> true

the returned value is no longer an instance of MyClass.

I've also tried @__proto__.first = @first in the constructor function and first: -> @slice.call @, 0, 1. But with no success.

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

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top