Lee2808 Lee2808 - 4 months ago 26
Javascript Question

Javascript: operator overloading

Been working with Javascript for a few days now and have got to a point where I want to overload operators for my defined objects.

After a stint on google searching for this it seems you can't officially do this, yet there are a few people out there claiming some long-winded way of performing this action.

Basically I've made a Vector2 class and want to be able to do the following:

var x = new Vector2(10,10);
var y = new Vector2(10,10);

x += y; //This does not result in x being a vector with 20,20 as it's x & y values.


Instead i'm having to do this:

var x = new Vector2(10,10);
var y = new Vector2(10,10);

x = x.add(y); //This results in x being a vector with 20,20 as it's x & y values.


Is there an approach I can take to overload operators in my Vector2 class? As this just looks plain ugly.

Answer

As you've found, JavaScript doesn't support operator overloading. The closest you can come is to implement toString (which will get called when the instance needs to be coerced to being a string) and valueOf (which will get called to coerce it to a number, for instance when using + for addition, or in many cases when using it for concatenation because + tries to do addition before concatenation), which is pretty limited. Neither lets you create a Vector2 object as a result.