So I'm making an expression parser in JavaScript and wanted to know: is there any way to assign an object's function to a logical/mathematical operator so that it gets called everytime the operator is used on that object?
I know that, for instance, whenever you try to concatenate an object to a string it automatically calls the object's .toString()
method.
For example, imagine you had objects with a this.number
attribute. I wanted to be able to do the following:
function MyObject(number) {
this.number = number;
}
var obj1 = new MyObject(2);
var obj2 = new MyObject(3);
obj1 *= obj2;
obj2 *= 3;
obj1.number; // Would return 6.
obj2.number; // Would return 9.
In this case, I would have overridden the *=
operator so that everytime it was called to assign a value to an instance of MyObject
it would multiply the instance's this.number
value by the value on its right (the primitive number value or the other instance's this.number
value).
Is there any way of acheiving this?
Any help would be awesome!
Thanks :-)