0

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 :-)

1 Answers1

1

You can create a .valueOf() function to return a numeric value. The runtime will call that in cases analogous to when it decides to call .toString() — that is, when it wants to coerce the object to a numeric value.

You cannot, however, force the runtime to treat an assignment specially, so you can't make

obj1 *= obj2;

work. The best you could do (with a .valueOf() implementation) would be:

obj1.number = obj1 * obj2;

The .valueOf() might look something like:

MyObject.prototype = {
  valueOf: function() { return this.number; }
};
Pointy
  • 405,095
  • 59
  • 585
  • 614