Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending a Javascript Array with additional methods and syntactic sugar

I need an array to store some geometrical data. I would like to simply inherit from the Array object and than extend it with a few new functions like "height" and "width" (sum of all children's heights/widths), but also with a few convenience methods like "insertAt" or "remove".

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

like image 566
Piotr Zurek Avatar asked Feb 25 '23 02:02

Piotr Zurek


2 Answers

You can always mixin your changes directly into Array, but that might not be the best choice given that it's not something every array should have. So let's inherit from 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
};
like image 58
chubbsondubs Avatar answered Apr 06 '23 00:04

chubbsondubs


Are you (maybe) applying Java concepts to Javascript?

You don't need to inherit from classes in Javascript, you just enrich objects.

So the best way in my world (a world full of people head-butting methods into objects) is:

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
}
like image 24
ZJR Avatar answered Apr 05 '23 23:04

ZJR