Overloading operators in javascript

Posted on Wednesday, April 01, 2009 2:11 PM

This is just a funny little experiment, but by defining a toString method on your custom objects, you can actually fake javascript into a basic form of operator overloading. Imagine the following:

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

var a = new Vector(1, 2, 3);
var b = new Vector(3, 2, 1);
var c = new Vector(1, 1, 1);

var d = a + b - c;

The d variable will now simply say NaN, because there is no way javascript would know how to sum up these vectors. However, if you define a toString method, you can get a result out of it. The trick is to return a number, and not a string (which toString would logically imply, normally):

Vector.prototype.toString = function() {
   return this.x + this.y + this.z;

Now, d would contain 9: 6 + 6 - 3, which is useless, but already a great leap from just NaN ;) All we need now is a way to encode the original vector into some kind of usable number, and get something out of it after others are added or subtracted. The answer is bitshifting; shift x 16 bits, y 8, and don't shift z.

Vector.prototype.toString = function() {
   var x = this.x << 16;
   var y = this.y << 8;
   var z = this.z;
   return x + y + z;

D now contains 197379, which at first may seem as useless as 9, but it actually represents the shifted sum. What we need to do is "decode" it, for instance using a static method on Vector:

Vector.parse = function(result) {
   var x = result >> 16;
   var y = (result -= (x << 16)) >> 8;
   var z = result - (y << 8);
   return new Vector(x, y, z);

var d = Vector.parse(a + b - c);

Et voila, d now contains a [3,3,3] vector.

Whereas this example makes totally no sense (and fails dramatically with multiplications and negative numbers), I could imagine there might be very specific cases in which this toString trick would be of some use ;)


# re: Overloading operators in javascript

4/1/2009 4:12 PM by Martin Reurings
Very cool, completely insane!

Also, did you test this in Chrome, Safari and IE, or is this only tested for Mozilla. Since it seems you've basically stumbled on a shortcut used by the javascript engine and not one that seems guaranteed across the various other implementations out there?

# re: Overloading operators in javascript

4/1/2009 4:38 PM by Peterned
Yup, works in all of them. The only "limitation" would be that you need a context in which the toString method is apt to be called, for instance concatenation with + like above. Dunno if I would base any vital stuff on it though ;)

# re: Overloading operators in javascript

4/2/2009 5:17 PM by norman
hey, have you tried valueOf instead of toString, it should works with multiplications and negative number.

I am using toString and valueOf to mimic the way of Property working in C#

Post Comment


ATTENTION: the code you need to copy is CaSe SeNsItIvE and is required to prevent spam.
Enter the code you see: