Overriding the == operator, like in Java/Lua/Python/whatever.

# Soni L. (10 years ago)

I've been looking and looking and looking and I couldn't find a way to override == to make 2 different instances of MyPoint compare == if they have the same coordinates. (I guess this also applies to String objects and stuff but I haven't tested that)

So how do I do this?

(PS: yes, I know, Java has an .equals method, not overridable ==, but it's basically the same thing)

# Caitlin Potter (10 years ago)

Unfortunately, there's no "real" way to do this as of yet, short of abusing ToPrimitive in certain cases, far from ideal.

I'm sure someone must have proposed it at some point, but perhaps not. In the mean time, it might be a nice feature of a compile-to-js language like coffeescript or typescript to experiment with

# Salvador de la Puente González (10 years ago)

Reimplement Object#valueOf() returning a string representation of your object.

See webreflection.blogspot.com.es/2010/10/javascript-coercion-demystified.html?m=1

Hope it helps.

# Michał Wadas (10 years ago)

It won't help because objects are ALWAYS compared by their identity. valeOf or toString will be used only in case of comparing object with primitive.

# Sebastian McKenzie (10 years ago)
# Andrea Giammarchi (10 years ago)

yep, I'm afraid this is described as such in the old post (and in specs) too:

Return true if x and y refer to the same object. Otherwise, return false

in your Point cases you can add .equals(otherPoint) in Point prototype otherwise use an utility that does similar thing Java does.

# Gary Guo (10 years ago)

I agree that use equals is a better choice. If operator overloading is implemented, you may experience inconsistency (different instance of builtin boxed values would be unequal according to default semantics, while after overloaded == operator it becomes equal.)

# Gary Guo (10 years ago)

(duplicate post)