1

Think of the Date() object:

thisDate = new Date()
thatDate = new Date()
thisDate - thatDate //returns some date object

Would it be possible for me to make some object, say Clovers() such that:

theseClovers = new Clovers();
theseClovers.count = 10;
thoseClovers = new Clovers();
thoseClovers.count = 4;

theseClovers - thoseClovers; //returns b = new Clovers(); b.count = 6

This is the way I envisage it (but is entirely hypothetical):

function Clovers(){
    onSubtract(b){
        if(b instanceOf someClass){
            return this.count - b.count
        }
    }
}
2
  • 2
    You can add a .valueOf() function to your objects (or a prototype); it's like .toString() except for numbers. Commented Feb 5, 2017 at 15:32
  • 1
    Possible duplicate of Overloading Arithmetic Operators in JavaScript? Commented Feb 5, 2017 at 15:42

1 Answer 1

2
function Clovers(val){
   this.count=val || 0;
}
Clovers.prototype.valueOf=function(){
 return this.count;
};

So it would work quite similar:

alert(new Clovers(new Clovers(10)-new Clovers(5)).count);
//or long written:
var a=new Clovers(10);
var b=new Clovers(4);
var c=new Clovers(a-b);
alert(c.count);

However, it might be better to have a custom addition function for that, similar to Array.prototype.concat:

 Clovers.prototype.concat=function(clover){
   return new Clovers(this.count-clover.count);
 };

Use like this:

var a=new Clovers(10);
var b=new Clovers(5);
var c=a.concat(b);
alert(c.count);

Thanks to Pointy and Karl-Johan Sjögren for the ideas...

Sign up to request clarification or add additional context in comments.

2 Comments

I actually prefer the first technique of overloading valueOf(). This is exactly how Date appears to work since Date()-Date() actually returns a value. So this is perfect! Thanks for the fish!
@Sancarn youre welcome ;) . please mark it as answer... and by the way, its not really overloading, its overriding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.