Can I define custom operator overloads in Javascript? [duplicate]

I agree that the equal function on the vector prototype is the best solution. Note that you can also build other infix-like operators via chaining.

function Vector(x, y, z) {
    this.x = x;
    this.y = y;
    this.z = z;
}

Vector.prototype.add = function (v2) {
    var v = new Vector(this.x + v2.x,
                       this.y + v2.y,
                       this.z + v2.z);
    return v;
}

Vector.prototype.equal = function (v2) {
    return this.x == v2.x && this.y == v2.y && this.z == v2.z;
}

You can see online sample here.

Update: Here’s a more extensive sample of creating a Factory function that supports chaining.

Leave a Comment