子类化Javascript数组。 TypeError:Array.prototype.toString不是通用的 [英] Subclassing Javascript Arrays. TypeError: Array.prototype.toString is not generic

查看:128
本文介绍了子类化Javascript数组。 TypeError:Array.prototype.toString不是通用的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从javascript Arrays继承和继承?

Is it possible to subclass and inherit from javascript Arrays?

我想拥有自己的自定义Array对象,它具有Array的所有功能,但是包含其他属性。如果实例是我的CustomArray,我将使用 myobj instanceof CustomArray 来执行特定操作。

I'd like to have my own custom Array object that has all the features of an Array, but contains additional properties. I'd use myobj instanceof CustomArray to perform specific operations if the instance is my CustomArray.

尝试子类化后并遇到一些问题,我发现这篇 Dean Edwards 文章指出这样做使用Array对象无法正常工作。事实证明,Internet Explorer无法正确处理它。但我也发现了其他问题(目前只在Chrome中测试过)。

After attempting to subclass and running into some problems, I found this Dean Edwards article that indicates doing this with Array objects doesn't work right. It turns out Internet Explorer doesn't handle it properly. But I'm finding other issues as well (only tested in Chrome so far).

以下是一些示例代码:

/** 
 *  Inherit the prototype methods from one constructor into another 
 *  Borrowed from Google Closure Library 
 */
function inherits(childCtor, parentCtor) {
    function tempCtor() {};
    tempCtor.prototype = parentCtor.prototype;
    childCtor.superClass_ = parentCtor.prototype;
    childCtor.prototype = new tempCtor();
    childCtor.prototype.constructor = childCtor;
},

// Custom class that extends Array class
function CustomArray() {
    Array.apply(this, arguments);
}
inherits(CustomArray,Array);

array = new Array(1,2,3);
custom = new CustomArray(1,2,3);

在Chrome的控制台中输入以下内容即可:

Entering the following in Chrome's console gives this output:

> custom
[]
> array
[1, 2, 3]
> custom.toString()
TypeError: Array.prototype.toString is not generic
> array.toString()
"1,2,3"
> custom.slice(1)
[]
> array.slice(1)
[2, 3]
> custom.push(1)
1
> custom.toString()
TypeError: Array.prototype.toString is not generic
> custom
[1]

显然,对象的行为不一样。我应该放弃这种方法,还是有办法实现我的目标 myobj instanceof CustomArray

Obviously, the objects don't behave the same. Should I give up on this approach, or is there some way to accomplish my goal of myobj instanceof CustomArray?

推荐答案

Juriy Zaytsev( @kangax )今天发布了一篇关于这个主题的非常好的文章。

Juriy Zaytsev (@kangax) just today released a really good article on the subject.

他探讨了各种替代方案,如Dean Edwards iframe借用技术,直接对象扩展,原型扩展和ECMAScript 5访问器属性的使用。

He explores various alternatives like the Dean Edwards iframe borrowing technique, direct object extension, prototype extension and the usage of ECMAScript 5 accessor properties.

最后没有完美的实施,每个都有自己的优点和缺点。

At the end there is no perfect implementation, each one has its own benefits and drawbacks.

绝对是非常好读:

  • How ECMAScript 5 still does not allow to subclass an array

这篇关于子类化Javascript数组。 TypeError:Array.prototype.toString不是通用的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆