0

根据这个答案,我想创建自己的子类Array

QArray = function() {
    Array.apply(this, arguments);
};
QArray.prototype = new Array();
QArray.prototype.constructor = QArray;

它按预期工作,方法调用有效,但构造函数没有链接到 Array。

// test constructor chaining
q = new QArray('1', '2', '3');
assert.equals('1', q[0]);      // => undefined
assert.equals(3, q.length);    // => 0
q = new QArray(10);
assert.equals(10, q.length);   // => 0

如果我替换QArray为 plain ,则此测试通过Array。不知怎的Array,似乎是个特例。(我在 Javascript 1.5 的 Rhino 1.6 中运行它。)如何修复我的自定义子类 Array?

4

1 回答 1

1

由于您的方法已经继承了数组方法,因此您可以使用修改键的数组方法,例如Array.prototype.push

QArray = function() {
    if (arguments.length == 1) this.length = arguments[0]; // Array constructor
    else this.push.apply(this, arguments);
};
QArray.prototype = new Array();
QArray.prototype.constructor = QArray;

q = new QArray('1', '2', '3');   // => [1,2,3]
assert.equals('1', q[0]);        // => true
assert.equals(3, q.length);      // => true
q = new QArray(10);              // => [,,,,,,,,,]
assert.equals(10, q.length);     // => true
q instanceof QArray;             // => true
q instanceof Array;              // => true

我曾经编写过一个自定义数组实现,它的行为就像一个真正的数组(包括lengthsetter/getter)。如果您需要灵感,请查看此答案

于 2012-06-15T20:38:25.133 回答