Is it possible to define custom operators between instances of a type in JavaScript?
For example, given that I have a custom vector class, is it possible to use
vect1 == vect2
to check for equality, whilst the underlying code would be something like this?
operator ==(a, b) { return a.x == b.x && a.y == b.y && a.z == b.z; }
(This is nonsense of course.)
Yes. Show activity on this post.
Operator overloading is only enabled for the classes that you specifically opt in to. To do this overloading, use a @use: operators declaration, follwed by a comma-separated list of classes that overload operators that you want to enable.
To overloading a prefix operator, we need to add a prefix keyword before a func . In the following example, I overload the - unary operator for a string, which will reverse the characters in a given string. <1> We add the prefix keyword to tell the compiler that this is intended to use as a prefix operator.
Rules for Operator Overloading:You can only overload existing operators. You can't overload new operators. Some operators cannot be overloaded using a friend function. However, such operators can be overloaded using member function.
I agree that the equal function on the vector prototype is the best solution. Note that you can also build other infix-like operators via chaining.
function Vector(x, y, z) { this.x = x; this.y = y; this.z = z; } Vector.prototype.add = function (v2) { var v = new Vector(this.x + v2.x, this.y + v2.y, this.z + v2.z); return v; } Vector.prototype.equal = function (v2) { return this.x == v2.x && this.y == v2.y && this.z == v2.z; }
You can see online sample here.
Update: Here's a more extensive sample of creating a Factory function that supports chaining.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With