Javascript: operator overloading

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. Similarly, Proxy (added in ES2015) lets you intercept various object operations (including property access), but again won’t let you control the result of += on Vector instances.


For people coming to this question who want a string or number as a result (instead of a Vector2), though, here are examples of valueOf and toString. These examples do not demonstrate operator overloading, just taking advantage of JavaScript’s built-in handling converting to primitives:

valueOf

This example doubles the value of an object’s val property in response to being coerced to a primitive, for instance via +:

Show code snippet

Or with ES2015’s class:

Show code snippet

Or just with objects, no constructors:

Show code snippet

toString

This example converts the value of an object’s val property to upper case in response to being coerced to a primitive, for instance via +:

Show code snippet

Or with ES2015’s class:

Show code snippet

Or just with objects, no constructors:

Show code snippet

Leave a Comment