Jump to content

Something like _toString when making a comparison?


MrFish

Recommended Posts

Is it possible to give an object a _toComparison value and have that automatically used when comparing 2 objects? For example:

c = new Calculation();c.multiply(10, 10);  c2 = new Calculation()c2.divide(1000, 10); if(c == c2) // 100 == 100{	 // do stuff}

This would be really helpful in my current situation where I'm not trying to compare if the object is the same as another but some contents of each. The function can be comparing simple data types as well as objects so I'm trying to keep for checking the type before comparing.

Edited by MrFish
Link to comment
Share on other sites

You can make an "equals()" method, it's a common practise.

if(c.equals(c2)) {	// Do something}

When you create the equals() method you decide which values to compare and what operations to do.

Link to comment
Share on other sites

You're talking about operator overloading. Unfortunately, Javascript does not support it. Certain operators will let you use a valueOf method to compare them, like arithmetic operators. Comparison operators won't call valueOf though. There's more information about that here: http://www.2ality.com/2011/12/fake-operator-overloading.html One possible example that might work for you is the answer given by Noah Freitas here: http://stackoverflow.com/questions/10539938/override-the-equivalence-comparison-in-javascript

Link to comment
Share on other sites

valueOf will work for me. I can just give my class a valueOf method. As long as it works the same with strings and integers it should be fine.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...