7

I have created new objects with Dojo.declare. How to overload operator == for objects ?

Damir
  • 54,277
  • 94
  • 246
  • 365

3 Answers3

9

You can't overload ==, but == has an implicit .toString() call, so whatever .toString() returns will allow you to effectively overload == (kinda):

function foo(){}
foo.prototype.toString = function(){ return 42; }

var x = new foo();
x == 42; // true

As for how to do this in Dojo, I don't use Dojo, sorry, but the gist is that you get a reference to whatever object is creates and add thatObject.prototype.toString as in my example.

  • 5
    For an object and a primitive, maybe. Though `valueOf` is what you would want to override. But not for two objects. `new String('x') != new String('x')` despite the fact that both objects' `toString` methods return the same value. – Mike Samuel Apr 11 '11 at 15:53
  • 1
    @Mike - meh. You're right. Object equality doesn't apply because there is only a check to the memory address... –  Apr 11 '11 at 16:28
  • 1
    even for object and primitive comparison the priority will be given to `valueOf`implementation. – Maksim Vi. Aug 07 '15 at 23:13
6

You can't. JavaScript doesn't support operator overloading.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

You can't in Javascript/ECMAscript. You can overload operators in ExtendScript from Adobe. See this example. Also see this blog entry (pro), or this (contra).

Lupus Ossorum
  • 450
  • 3
  • 16
KooiInc
  • 119,216
  • 31
  • 141
  • 177