Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you override what == does in Javascript? [duplicate]

In Python, it's possible to override what == does by defining a __eq__ method for your class.

Is it possible to do something similar in Javascript? If so, how do you do it?

My understanding is that, by default (and maybe always, if you can't override it), Javascript just checks to see if two objects reside at the same address when you do a ==. How can I get the address directly?

I'm asking all of this because I'm trying to debug some code someone who's long gone wrote. As far as I can tell, two objects are identical, and yet == is returning false. I'm trying to find why... I'm wondering if maybe == was overridden someplace (but it's a big codebase and I don't know what to search for) or if or if maybe the object was duplicated, so they exist at different addresses despite being identical as far as I can tell. Knowing how to get the address would help with confirming that theory and give me a lead to hunt down the problem.

like image 479
ArtOfWarfare Avatar asked Jul 26 '16 19:07

ArtOfWarfare


People also ask

Can we override equivalence comparison in JavaScript?

I'm afraid you cannot achieve such thing in Javascript. See http://www.2ality.com/2011/12/fake-operator-overloading.html for some more details.

Can I override a function in JavaScript?

It is true that JavaScript supports overriding, not overloading. When you define multiple functions that have the same name, the last one defined will override all the previously defined ones and every time when you invoke a function, the last defined one will get executed.

What is == and === in JavaScript?

The main difference between the == and === operator in javascript is that the == operator does the type conversion of the operands before comparison, whereas the === operator compares the values as well as the data types of the operands.

Why does JavaScript have 3 equal signs?

JavaScript === (Triple Equals) The triple equals sign in JavaScript means “equality without type coersion”. That means, the type and values must both be equal. Take for example the scenario where 0 is false. If we compare the same 0 and false with ===, we have false returned.


2 Answers

Not typically. JS does not allow operator overloading or operators-as-methods.

There are certain operators that call toString or valueOf internally, which you can override on your own classes, thus influencing the behavior.

like image 147
ssube Avatar answered Oct 11 '22 10:10

ssube


No, it is not possible to override any operators directly in JavaScript.

like image 39
Whothehellisthat Avatar answered Oct 11 '22 08:10

Whothehellisthat