Extending Javascript Array with Extra Methods and Syntactic Sugar

I need an array to store some geometric data. I would just like to inherit an Array object and extend it with a few new functions, such as height and width (the sum of all the heights and widths of children), but also with a few convenient methods like insertAt or insertAt ", delete."

What is the best way to do this without modifying the original Array object (Array.prototype.myMethod)?

+4
source share
3 answers

You can always mix your changes directly into Array, but this may not be the best choice, given that this is not what every array should have. So let's inherit from an array:

// create a constructor for the class function GeometricArray() { this.width = 0; this.height = 0; } // create a new instance for the prototype so you get all functionality // from it without adding features directly to Array. GeometricArray.prototype = new Array(); // add our special methods to the prototype GeometricArray.prototype.insertAt = function() { ... }; GeometricArray.prototype.remove = function { ... }; GeometricArray.prototype.add = function( child ) { this.push( child ); // todo calculate child widths/heights }; 
+5
source

Did you apply Java concepts to Javascript?

You do not need to inherit classes in Javascript, you just enrich objects.

Thus, the best way in my world (a world full of people who use dizziness methods in objects):

 function GeometricArray() { var obj=[] obj.height=function() { // wibbly-wobbly heighty things for(var i=0;i<this.length;i++) { // ... } } obj.width=function() { // wibbly-wobbly widy things // ... } // ...and on and on... return obj } 
+2
source

You can use prototyping to place these functions in an array.

To add a height function, for example, follow these steps:

 Array.prototype.height = function() { //implementation of height } 
+1
source

Source: https://habr.com/ru/post/1340109/


All Articles