7

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.

ArtOfWarfare
  • 20,617
  • 19
  • 137
  • 193
  • It's not possible to override operators in JavaScript. If you are using `==` or `===` on two objects, it will return `true` iff they are the same reference. – JLRishe Jul 26 '16 at 19:34
  • The objects _look_ the same, but are not actually the same object in memory. One way of double-checking this is by adding a property with a value to one, and see if it appears on the other. If not, they are different objects. – Whothehellisthat Jul 26 '16 at 19:36
  • Here: https://stackoverflow.com/q/10539938/632951 – Pacerier Sep 19 '17 at 00:14

2 Answers2

5

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.

ssube
  • 47,010
  • 7
  • 103
  • 140
  • 1
    Interesting. Does that apply to `==`? – ArtOfWarfare Jul 26 '16 at 19:35
  • @ArtOfWarfare Sometimes. See [Abstract Equality Comparison](http://www.ecma-international.org/ecma-262/6.0/#sec-abstract-equality-comparison) which explains how different operand type-pairings are coerced for comparison with `==`, which sometimes uses the operation [ToPrimitive](http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive) which sometimes calls `valueOf` or `toString`. For an object-to-object comparison, though, `==` does direct identity comparison ("Are these objects really the same one object?") – apsillers Jul 26 '16 at 19:38
  • @ArtOfWarfare sometimes, as apsillers elaborated on. I need to go through the spec and see which operators do, but that's a bit extensive to do while at work (sorry). – ssube Jul 26 '16 at 19:41
  • @apsillers, ssube. Don't think there's a way to affect `==` if both sides are objects. – Pacerier Sep 19 '17 at 00:03
1

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

Whothehellisthat
  • 2,072
  • 1
  • 14
  • 14