是否可以子类化并继承自 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/