Can I create a class that creates objects who have special context? (like string or number contexts).
class Unit extends Number {
constructor(value, symbol) {
super(value)
this.symbol = symbol
}
valueOf() {
return parseFloat(this.toPrecision(2))
}
toString() {
return `${this.valueOf()} ${this.symbol}`
}
}
let meter = new Unit(1, 'm')
console.log('example of number context that uses valueOf()')
console.log(Number(meter)) // Number(1)
console.log(1 + meter) // Number(2)
console.log(2 * meter) // Number(2)
console.log('example of string context that uses toString()')
console.log(String(meter)) // String('1 m')
console.log(`string: ${meter}`) // String('string: 1 m')
console.log(`and what I'm trying to do (Unit context), but instead it works like number context`)
console.log(meter + 1) // Unit(2, 'm')
const square_meter = meter * meter
console.log(square_meter) // Unit(1, 'm2')
console.log(square_meter / meter) // Unit(1, 'm')
So, what I'm trying to do is check if object of class Unit
is used with an operator (and which operator) against another Unit, Number or String and produce different result depending on that.
My question is, if something like that is possible with JavaScript?