1

I know it is probably stupidly hard to do, but is there a way to override JavaScript's automatic type conversion? Say I have

class Foo {
  constructor() {
    this.foo = "foo"
  }
}

And I want to do something like this:

let foo1 = new Foo();
let foo2 = new Foo();

let diff = foo2 - foo3;

Just like math with Date in JavaScript:

let d1 = new Date();
setTimeout(() => {
  let d2 = new Date();
  d2 - d1; //500
}, 0);

If it helps, I am trying to work with matrices. If this is too vague, please let me know and I will try to supply any information you need.

ErrorGamer2000
  • 295
  • 3
  • 8
  • 1
    Does this answer your question? [Javascript: operator overloading](https://stackoverflow.com/questions/19620667/javascript-operator-overloading) – virchau13 Apr 27 '21 at 01:44
  • You should read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#defining_getters_and_setters – Daniel Tate Apr 27 '21 at 01:45

1 Answers1

0

Javascript does not have any type of "type conversion"; as it doesn't have "types" to begin with. While javascript does know the class keyword in later versions, this is just syntactic sugar for programmers coming from class-based systems such as Java. Under the hood, Javascript does not know classes (or types), it only knows objects and prototypes.

This implies: when using numeric operators such as - on objects, no type converison is done. However, as - can only work on numerical values, objects passed into it need to be converted to numeric values. This is done by calling valueOf() internally - usually, the implementation of this method is provided by Object.prototype. (Object.prototype.valueOf on MDN)

To change how a value is converted into a numeric value, you can implement valueOf on your own. If you do so, your objects implementation will be used instead of the one defined by Object, as your implementation will be "higher" on the prototype chain. (In "traditional", class-based system, this equals "overriding").

class Foo {
    constructor() {
       this.foo = "foo"
    }
    valueOf() {
        // do math to convert Matrix into primitive
        return convertedValue;
    }

This example should make it clear that there is no way to actually do matrix subtraction using the - operator - it only works on numeric values. So if you do NOT intend to subtract, say, eigen-values of matrices but actually subtract one matrix from an equal-dimensioned different matrix, then this will not work.

Instead, you could supply a subtract() method that will take a second matrix and return the result.

Johannes H.
  • 5,875
  • 1
  • 20
  • 40