我可以用自定义构造函数创建自定义数组吗?

时间:2021-05-27 20:14:22

I want to create a class that would inherit everything from Array class but has its own constructor.

我想创建一个类,它将继承Array类中的所有内容,但是有自己的构造函数。

The idea is something like this:

这个想法是这样的:

function Array2(value) 
{
    this.push(value*value);
};
Array2.prototype = new Array();
Array2(4);

Obviously this doesn't work because "this.push" doesn't work, because Array2 is not yet based on Array.

显然这不起作用,因为“this.push”不起作用,因为Array2还没有基于Array。

1 个解决方案

#1


your code doesn't work because you didn't call it with new keyword which means that this is equal to window.

你的代码不起作用,因为你没有用new关键字调用它,这意味着它等于window。

var a = new Array2(4);

#1


your code doesn't work because you didn't call it with new keyword which means that this is equal to window.

你的代码不起作用,因为你没有用new关键字调用它,这意味着它等于window。

var a = new Array2(4);