子类化JavaScript数组 - 不传递给数组的构造函数参数 [英] Subclassing JavaScript arrays - constructor arguments not passing to array

查看:82
本文介绍了子类化JavaScript数组 - 不传递给数组的构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想继承javascript数组并将构造函数参数传递给数组。我拥有的是:

I want to subclass a javascript Array and pass constructor arguments to the array. What I have is:

function SubArray(arguments) {
    Array.apply(this, arguments);
}

SubArray.prototype = Array.prototype;

测试并不表示参数传递给数组

Test does not indicate that arguments are being passed to the Array

var x = new SubArray("One", "Two", "Three");
// Object[]
// x.length = 0

当我用数组做这个时我得到这个

Whereas when I do this with an Array I get this

var x = new Array("One", "Two", "Three");
// Object["One", "Two", "Three"]
// x.length = 3

我做错了什么?

推荐答案

ES6



在ES6中,您可以使用语法扩展 Array

class SubArray extends Array {
    constructor() {
        super(...arguments);
    }
    first() {
        return this[0];
    }
}

length 将作为预期

var sa = new SubArray('foo', 'bar');
sa[2] = 'baz';
sa.length; // 3
sa.first(); // "foo"
sa instanceof SubArray; // true






Pre-ES5



直到并包括ES5,没有办法以通常的构造函数原型方式干净地扩展 Array 而不会丢失功能,而是你必须向Array实例添加属性


Pre-ES5

Up to and including ES5 there is no way to cleanly extend Array in the usual constructor-prototype way without losing functionality, instead you have to add properties to an Array instance

function SubArray() {
    var arr = Array.apply(null, arguments);
    arr.first = function () {return this[0];};
    return arr;
}

使用它不再需要 new 从函数返回 Object instanceof 将无法确定 SubArray

Using this no longer requires new as an Object is returned from the function, and instanceof will not be able to determine SubArray.

var sa = SubArray('foo', 'bar');
sa[2] = 'baz';
sa.length; // 3
sa.first(); // "foo"
sa instanceof SubArray; // false -- this gets broken






ES5(慢速)



在行为比速度更重要的ES5环境中,您可以使用 Object.setPrototypeOf (请参阅MDN警告) ,这是有点黑客,看起来像

function SubArray() {
    var arr = Array.apply(null, arguments);
    Object.setPrototypeOf(arr, SubArray.prototype);
    return arr;
}
SubArray.prototype = Object.create(Array.prototype);
SubArray.prototype.first = function () {return this[0];};

再次,不再需要 new 但这次实例的行为与正常情况下的预期完全相同。

Again, new is no-longer required but this time the behaviour of instances is exactly as would be expected if it was extended normally.

var sa = SubArray('foo', 'bar');
sa[2] = 'baz';
sa.length; // 3
sa.first(); // "foo"
sa instanceof SubArray; // true

这篇关于子类化JavaScript数组 - 不传递给数组的构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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