Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define custom operator overloads in Javascript? [duplicate]

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.)

like image 535
pimvdb Avatar asked Jan 15 '11 14:01

pimvdb


People also ask

Can you have multiple operator overloads?

Yes. Show activity on this post.

Does JavaScript allow user defined operator overloading?

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.

How do you do custom operator overloading?

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.

Can we overload only existing 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.


1 Answers

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.

like image 137
mckoss Avatar answered Sep 28 '22 08:09

mckoss