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
        }
    }
}
Sancarn
  • 2,575
  • 20
  • 45
  • 2
    You can add a `.valueOf()` function to your objects (or a prototype); it's like `.toString()` except for numbers. – Pointy Feb 05 '17 at 15:32
  • 1
    Possible duplicate of [Overloading Arithmetic Operators in JavaScript?](http://stackoverflow.com/questions/1634341/overloading-arithmetic-operators-in-javascript) – Karl-Johan Sjögren Feb 05 '17 at 15:42

1 Answers1

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...

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 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 Feb 05 '17 at 16:01
  • @Sancarn youre welcome ;) . please mark it as answer... and by the way, its not really overloading, its overriding – Jonas Wilms Feb 05 '17 at 16:01