扩展proto数组

时间:2017-12-21 14:41:39

标签: javascript prototype prototypal-inheritance prototype-programming

我对原型有疑问。 我正在做一个项目,我想为Array创建一个小函数库,我有3种可能性。

扩展数组原型(但我知道不建议这样做)

Array.prototype.arrayMax = function () {
    return Math.max(...this)
}

创建数组的子类。

function MyArray(...args) {
    Object.setPrototypeOf(args,MyArray.prototype)
    return args;
}
MyArray.prototype = Object.create(Array.prototype);
MyArray.prototype.arrayMax = function () {
    return Math.max(...this)
}

创建一个文件,其中包含Array传递参数的不同函数。

const arrayMin = arr => Math.min(...arr);

如果我们采用这个选项,我使用JS O.O和我的目录结构是 Structure of directory

哪里可以添加此存档js。

什么是最正确的选项?

1 个答案:

答案 0 :(得分:1)

目前第三个选项(实现函数)是最优选的,因为向内置原型添加函数是个坏主意:如何解决歧义?如果其他库为Array.prototype添加了具有相同名称的函数,会发生什么?

第二个选项不会出现歧义问题,但在#1和#2中,您将失去使用语法声明数组的机会(即[])。

关于在哪里放置该代码,它是主观的。我会把它放在一个名为commonshared的文件夹中,或者只放在工作区的根目录下。