正确地扩展数组,保留子类的实例 [英] Extending an Array properly, keeping the instance of subclass
问题描述
我写了一个类试图用自定义类扩展本地的Javascript 数组
类,让我们称之为 MyClass
。这基本上是它的样子:
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
正常工作。
问题是如果我运行:
myInstance.first()
> ["1"] // as expected
myInstance.first() instanceof MyClass
> false // not expected
myInstance.first() instanceof Array
> true
返回的值不再是MyClass的实例。
the returned value is no longer an instance of MyClass.
我也尝试了 @__ proto __。first = @first
在构造函数和 first: - > @ slice.call @,0,1
。但是没有成功。
I've also tried @__proto__.first = @first
in the constructor function and first: -> @slice.call @, 0, 1
. But with no success.
为什么 myInstance.first()instanceof MyClass
return true
?
Why doesn't myInstance.first() instanceof MyClass
return true
?
推荐答案
为什么不
myInstance.first()instanceof MyClass
return true?
Why doesn't
myInstance.first() instanceof MyClass
return true?
因为
调用 slice
和 Array.prototype.slice
总是返回 Array
。您将需要使用一个方法将其覆盖,再次将它包装在 MyClass
中:
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
请注意, subclassing Array
无效。
And notice that subclassing Array
does not work.
这篇关于正确地扩展数组,保留子类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!