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

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

问题描述

是否可以从 javascript 数组子类化和继承?

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.

绝对是一本非常好的读物:

Definitely a really good read:

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

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