Extending an Array properly, keeping the instance of subclass

不想你离开。 提交于 2020-01-17 00:27:09

问题


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?


回答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.



来源:https://stackoverflow.com/questions/22487836/extending-an-array-properly-keeping-the-instance-of-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!