Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a reasonable way to 'subclass' a javascript array?

I realize that, strictly speaking, this is not subclassing the array type, but will this work in the way one might expect, or am I still going to run into some issues with .length and the like? Are there any drawbacks that I would not have if normal subclassing were an option?

        function Vector()
        {
            var vector = [];
            vector.sum = function()
            {
                sum = 0.0;
                for(i = 0; i < this.length; i++)
                {
                    sum += this[i];
                }
                return sum;
            }            
            return vector;
        }

        v = Vector();
        v.push(1); v.push(2);
        console.log(v.sum());
like image 888
shino Avatar asked Jan 21 '11 16:01

shino


2 Answers

I'd wrap an array inside a proper vector type like this:

window.Vector = function Vector() {
  this.data = [];
}

Vector.prototype.push = function push() {
  Array.prototype.push.apply(this.data, arguments);
}

Vector.prototype.sum = function sum() {
  for(var i = 0, s=0.0, len=this.data.length; i < len; s += this.data[i++]);
  return s;
}

var vector1 = new Vector();
vector1.push(1); vector1.push(2);
console.log(vector1.sum());

Alternatively you can build new prototype functions on arrays and then just use normal arrays.

If you are consistent with naming the arrays so they all start with a lowercase v for example or something similar that clearly mark them aw vector and not normal arrays, and you do the same on the vector specific prototype functions, then it should be fairly easy to keep track of.

Array.prototype.vSum = function vSum() {
  for(var i = 0, s=0.0, len=this.length; i < len; s += this[i++]);
  return s;
}

var vector1 = [];
vector1.push(1); vector1.push(2);
console.log(vector1.vSum());
like image 81
Martin Jespersen Avatar answered Nov 11 '22 05:11

Martin Jespersen


EDIT -- I originally wrote that you could subclass an Array just like any other object, which was wrong. Learn something new every day. Here is a good discussion

http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/

In this case, would composition work better? i.e. just create a Vector object, and have it backed by an array. This seems to be the path you are on, you just need to add the push and any other methods to the prototype.

like image 34
hvgotcodes Avatar answered Nov 11 '22 05:11

hvgotcodes