How you can determine how objects are compared in JavaScript

I want to define a JavaScript class, Foo.

Foo = function(value){
    this.value = value;
};

I will create "instances" of my foo:

foo1 = new Foo(1);
foo2 = new Foo(1);

and I want my Foo instances to be compatible with each other using the standard equality operator:

foo1 == foo2;      // this should be true

I can not find a way to do this. I thought I was having something with a function valueOf(), but this is only useful when one side of the comparison is primitive, and not the same as above, where both objects are of type.

I missed something really simple, similar to Ruby's

def ==(obj); end
+5
source share
4 answers

JavaScript . . , .

+6

...

Foo = function (value){
    this.value = value;
};

toString :

Foo.prototype.toString = function( ){ return this.value.toString(); }

:

foo1 = new Foo(1);
foo2 = new Foo(1);

, javascript , :

alert( ""+foo1 === ""+foo2 ); //Works for strings and numbers

, :

alert( foo1.toString() === foo2.toString() ); //Works for strings and numbers

, unary + :

alert( +foo1 === +foo2 ); //Works for numbers

toString, , :

Foo.prototype.equals=function(b){return this.toString() === b.toString();}

:

alert ( foo1.equals(foo2) );

toString, :

alert(foo1); // Alerts the value of foo1 instead of "[Object object]"
alert("foo1: " + foo1); // Alerts "foo1: 1". Useful when debugging. 
+4

, javascript. , . isEqual()

+1
source

JavaScript in this respect is similar to the namesake of Java: there is no operator overload. Use your own method instead, for example equals().

0
source

All Articles