Overloading Arithmetic Operators in JavaScript?

As far as I’m aware, Javascript (at least as it exists now) doesn’t support operator overloading.

The best I can suggest is a class method for making new quota objects from several others. Here’s a quick example of what I mean:

// define an example "class"
var NumClass = function(value){
    this.value = value;
}
NumClass.prototype.toInteger = function(){
    return this.value;
}

// Add a static method that creates a new object from several others
NumClass.createFromObjects = function(){
    var newValue = 0;
    for (var i=0; i<arguments.length; i++){
        newValue += arguments[i].toInteger();
    }
    return new this(newValue)
}

and use it like:

var n1 = new NumClass(1);
var n2 = new NumClass(2);
var n3 = new NumClass(3);

var combined = NumClass.createFromObjects(n1, n2, n3);

Leave a Comment