Search code examples
javascriptprototypeprototypal-inheritanceprototype-programming

Extend proto Array


I have a question with the prototypes. I'm doing a project and I want to create a small library of functions for Array, I have 3 possibilities.

Extend the Array prototype (But I understand that it is not recommended)

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

Create a subclass of Array.

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

Create a file with the different functions where the Array passes through the parameter.

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

If we take this option, I use JS O.O and my structure of directory is Structure of directory

Where can add I this archive js.

What would be the most correct option?


Solution

  • Currently the third option (implementing functions) is the optimal one because adding functions to built-in prototypes is a bad idea: how do you solve ambiguities? What would happen if other library adds a function with the same name to Array.prototype?

    The second option wouldn't have the ambiguity issue, but in #1 and #2 you lose the chance to use syntax to declare arrays (i.e. []).

    About where to place that code, it's subjective. I would put it in a folder called common or shared, or just at the root of your workspace.