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.
The best you can do if you want to stick with the ==
operator:
function Vector(x, y, z) { this.x = x; this.y = y; this.z = z;}Vector.prototype.toString = function () { return this.x + ";" + this.y + ";" + this.z;};var a = new Vector(1, 2, 3);var b = new Vector(1, 2, 3);var c = new Vector(4, 5, 6);alert( String(a) == b ); // truealert( String(a) == c ); // falsealert( a == b + "" ); // true again (no object wrapper but a bit more ugly)
No, JavaScript doesn’t support operator overloading. You will need to write a method that does this:
Vector.prototype.equalTo = function(other) { if (!(other instanceof Vector)) return false; return a.x == b.x && a.y == b.y && a.z == b.z;}
Then you can use that method like:
vect1.equalTo(vect2)