Can I define custom operator overloads in Javascript?

pimvdb picture pimvdb · Jan 15, 2011 · Viewed 12.8k times · Source

Is it possible to define custom operators between instances of a type in JavaScript?

For example, given that I have a custom vector class, is it possible to use

vect1 == vect2

to check for equality, whilst the underlying code would be something like this?

operator ==(a, b) {
    return a.x == b.x && a.y == b.y && a.z == b.z;
}

(This is nonsense of course.)

Answer

mckoss picture mckoss · Jan 15, 2011

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.