Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overload operator equality for JavaScript objects

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

like image 742
Damir Avatar asked Apr 11 '11 08:04

Damir


People also ask

What is == and === in JavaScript?

operators in javascript are used to compare two values. The == operator checks if two values are equal. The != operator checks if two values are not equal.

What is === in JavaScript?

The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.

Can we overload operator in JavaScript?

Operator Overloading in JavaScript, yes you can!


2 Answers

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.

like image 72
Nobody Avatar answered Sep 19 '22 12:09

Nobody


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

like image 41
Quentin Avatar answered Sep 20 '22 12:09

Quentin