Friday, June 13, 2014

Operator overloading with JavaScript

JavaScript happens to have an extremely powerful OOP tool-set that is quite unknown. I am surprised every day by the power and flexibility of it.

One of the things I didn't knew is possible at all with JavaScript was operator overloading.
And this is understandable - JavaScript doesn't have strict variable types. Therefore any type of polymorphism is very hard to be implemented, as it is bound to the object/variable types.

However, you can easily do polymorphism with JavaScript and as it happens, you can easily do operator overloading too :)

How that works?

It is really easy - JavaScript retrieve the value of an Object using the valueOf method. And every object has valueOf with the exception of few primitive types (as in Java and C++). Therefore you can use that to do operator oveloading.

Let me show you an example:

~$ node
> a={}
{}
> a == 3
false
> a.valueOf = function() { return 3 }
[Function]
> a == 3
true

And the best is that you can do that to the prototype (or to the inherited object):

~$ node
> {} == 3
false
> Object.prototype.valueOf = function() { return 3 }
[Function]
> {} == 3
true

1 comment: