Overloading Arithmetic Operators in JavaScript?
Unfortunately no.
For fallbacks, if you arranged the return values, you could use method chaining
var q4 = q1.plus(p2).plus(q3);
Since everyone down voted my other answer I wanted to post proof of concept code which does in fact work as intended.
This has been tested in chrome and IE.
//Operator Overloading
var myClass = function () {
//Privates
var intValue = Number(0),
stringValue = String('');
//Publics
this.valueOf = function () {
if (this instanceof myClass) return intValue;
return stringValue;
}
this.cast = function (type, call) {
if (!type) return;
if (!call) return type.bind(this);
return call.bind(new type(this)).call(this);
}
}
//Derived class
var anotherClass = function () {
//Store the base reference
this.constructor = myClass.apply(this);
var myString = 'Test',
myInt = 1;
this.valueOf = function () {
if (this instanceof myClass) return myInt;
return myString;
}
}
//Tests
var test = new myClass(),
anotherTest = new anotherClass(),
composed = test + anotherTest,
yaComposed = test.cast(Number, function () {
return this + anotherTest
}),
yaCComposed = anotherTest.cast(Number, function () {
return this + test;
}),
t = test.cast(anotherClass, function () {
return this + anotherTest
}),
tt = anotherTest.cast(myClass, function () {
return this + test;
});
debugger;
If someone would be so kind as to give a technical explanation WHY this is not good enough I would be happy to hear it out!
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);
You can implicitly convert to integer or string, your objects.
Objects are only implicitly converted if JavaScript expects a number or a string. In the former case, the conversion takes three steps:
1.- Call valueOf()
. If the result is primitive (not an object) then use it and convert it to a number.
2.- Otherwise, call toString()
. If the result is primitive, use it and convert it to a number.
3.- Otherwise, throw a TypeError
.
Example for step 1:
3 * { valueOf: function () { return 5 } }
If JavaScript converts to string, steps 1 and 2 are swapped: toString() is tried first, valueOf() second.
http://www.2ality.com/2013/04/quirk-implicit-conversion.html