javascript - 子类化 Javascript 数组。 TypeError : Array. prototype.toString 不是通用的

标签 javascript inheritance

是否可以子类化并继承自 javascript 数组?

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

在尝试子类化并遇到一些问题后,我发现了这个 Dean Edwards指示使用数组对象执行此操作不正确的文章。事实证明 Internet Explorer 无法正确处理它。但我也发现了其他问题(目前仅在 Chrome 中测试过)。

下面是一些示例代码:

/** 
 *  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 的控制台中输入以下内容会得到以下输出:

> 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 目标?

最佳答案

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

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

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

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

关于javascript - 子类化 Javascript 数组。 TypeError : Array. prototype.toString 不是通用的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3261587/

相关文章:

c# - EntityFramework 代码优先继承,在派生类上具有急切的包含关系

c# - 使用其中的代码创建 mustoveride 函数

javascript - 在子 Controller 中触发时,Ionic AngularJS 父动画无法正确运行

javascript - 带选择器的 JQuery prev()

javascript - 在 Bootstrap 网站上放置背景

java - 协变结构因 Java 中的捕获错误而失败

c++ - 将 shared_ptr vector 填充到 Base & Derived 对象的函数模板

javascript - SignalR 客户端不触发服务器代码

javascript - 在 javascript 中使用 handlebars 模板变量

swift - 从 CollectionViewCell 呈现 View 时,调用中缺少参数 'coder' 的参数