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.
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.
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.
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.
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.
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.
No, it is not possible to override any operators directly in JavaScript.
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