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.