You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Apr 3, 2025. It is now read-only.
There is already the possibility to trap certain operators on objects and similar (e.g. () or new) by using Proxy traps. For consistency it would seem sensible to put the overloading of other operators there as well.
It could work like this:
classVector{constructor(x,y){this.x=x;this.y=y;}}Vector.prototype=newProxy(Vector.prototype,{add(target,other){if(typeofother==="number"){returnnewVector(target.x+other,target.y+other);}elseif(typeofother==="object"&&typeofother.x==="number"&&typeofother.y==="number"){// TODO: add case for bigint?returnnewVector(target.x+other.x,target.y+other.y);}else{thrownewError("unsupported operand provided for addition of vector");}}// TODO: add further operators});constone=newVector(1,1);consttwo=one+one;console.log(two);// Vector { x: 2, y: 2 }constthree=one+2;console.log(three);// Vector { x: 3, y: 3 }constbad=3+one;// coercion appearing as number has no overload (and cannot have one) for objectsconsole.log(bad);// 3[object Object]
The "sugared" version is to be defined.
This would of course bring some further changes to the proposal, most notably that the overloaded operators would be inherited and always be present as there is no "with" to explicitly enable them. However, that would probably not be a problem as it is in line with how Proxies (and thus our currently limited operator overloading) works.