Search code examples
javascriptconstructorarithmetic-expressions

How can I write constructor within an arithmetic expression?


I want to cut down on ugly code in JavaScript, especially relating to constructors.

I have a vector defined as:

function Vector2(X, Y) {
    this.x = 0.0;
    this.y = 0.0;

    if (X)
        this.y = Y;
    if (Y)
        this.y = Y;
}

Right now, in order to add two vectors together, I must write:

var vector1 = new Vector2(1.0, 0.5);
var vector2 = new Vector2(4.5, 1.0);

vector1.x += vector2.x;
vector1.y += vector2.y;

What I want to make the code prettier, easier to read, and make a smaller file when many constructors are used. What I want to be able to write is:

vector1 += vector2;

Thank you in advance for any help.


Solution

  • You could have this :

    function Vector(X, Y) {
        this.x = X || 0.0; // yes, I simplified a bit your constructor
        this.y = Y || 0.0;
    }
    Vector.prototype.add = function(v) {
       this.x += v.x;
       this.y += v.y; 
    }
    

    And you'd just have to do

    var vector1 = new Vector(4,4);
    var vector2 = new Vector(1,3);
    vector1.add(vector2);