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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top