MrFish Posted March 19, 2013 Share Posted March 19, 2013 (edited) 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 March 19, 2013 by MrFish Link to comment Share on other sites More sharing options...
Ingolme Posted March 19, 2013 Share Posted March 19, 2013 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 More sharing options...
justsomeguy Posted March 19, 2013 Share Posted March 19, 2013 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 More sharing options...
MrFish Posted March 19, 2013 Author Share Posted March 19, 2013 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 More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now