Value types versus .valueOf
# Brendan Eich (11 years ago)
Alex Vincent wrote:
var x = new SmallDecimal(2); var y = new SmallDecimal(3); [x < y, x > y, x == y, x <= y, x >= y, x != y]
valueOf doesn't work for SmallDecimal(2) == SmallDecimal(2), though. You have to hash-cons, which kils performance.
String relational order is wrong for numeric types, to boot:
js> '10' < '2'
true
So valueOf is a no-go.
I like the idea of value types, but I wonder if, for terminating decimal numbers, the .valueOf() method from Object.prototype might be sufficient for many operations.
Example:
function SmallDecimal(k) { this.__value__ = k; } SmallDecimal.prototype.valueOf = function() { return this.__value__.toString(10); } var x = new SmallDecimal(2); var y = new SmallDecimal(3); [x < y, x > y, x == y, x <= y, x >= y, x != y] /* true,false,false,true,false,true */
I still want to see value types go forward: in the above example, x + y would result in "23", where x - y === -1. Perhaps .valueOf could be used in testing simple value types implementations.