【发布时间】:2015-01-16 13:55:54
【问题描述】:
所以我阅读了一些关于subclassing Array in JavaScript 的博客文章、SO 线程和其他讲座。对该主题的一般看法是,没有办法创建具有某种缺点的子类。
在尝试一些事情时,我为自己想出了这个解决方案:
// This is the constructor of the new class.
function CustomArray() {
// The "use strict" statement changes the way the "magic" variable
// "arguments" works and makes code generally safer.
"use strict";
// Create an actual array. This way the object will treat numeric
// properties in the special way it is supposed to.
var arr = [],
i;
// Overwrite the object's prototype, so that CustomArray.prototype is
// in the prototype chain and the object inherits its methods. This does
// not break the special behaviour of arrays.
Object.setPrototypeOf(arr, CustomArray.prototype);
// Take all arguments and push them to the array.
for (i = 0; i < arguments.length; i++) {
arr.push(arguments[i]);
}
// Return the array with the modified prototype chain. This overwrites
// the return value of the constructor so that CustomArray() really
// returns the modified array and not "this".
return arr;
}
// Make CustomArray inherit from Array.
CustomArray.prototype = Object.create(Array.prototype);
// Define a method for the CustomArray class.
CustomArray.prototype.last = function () {
return this[this.length - 1];
};
var myArray = new CustomArray("A", "B", 3);
// [ "A", "B", 3 ]
myArray.length;
// 3
myArray.push("C");
// [ "A", "B", 3, "C" ]
myArray.length;
// 4
myArray.last();
// "C"
我的问题是:这段代码有什么问题吗?在这么多人在我之前搜索之后,我很难相信我想出了“唯一的解决方案”。
【问题讨论】:
-
这不是您问题的答案,但请注意您链接到的文章标题为“ECMAScript 5 如何仍然不允许子类化数组”和您的解决方案使用 ECMAScript 6 函数。
-
@apsillers 你是对的。我什至没有想到这一点。但这篇文章似乎仍然适用。描述的问题在 ECMAScript 6 中仍然相同。
-
@apsillers 这有点尴尬。当我为这个问题构建简化示例时,这条线不知何故丢失了。我编辑了问题以包含代码行。
标签: javascript arrays prototype