I want to create a class that has several public variables and methods,but behaves as number when arithmetic operators are applied.Example :
a = new hyperNum(4)
a.func(4)
a.assign(2.0)
alert(a + 1.0) `//3.0`
I know I can just overload the Number object but then I think that there would be a certain overhead for all numbers.
When I tried to inherit from Number ,I got an error:
function hyperNum () {}
hyperNum.prototype = new Number();
hyperNum.prototype.z = function(q){this.q = q;}
h = new hyperNum(2);
h+5
/* error:
TypeError: Number.prototype.valueOf is not generic
at Number.valueOf (native)
at Number.ADD (native)
at [object Context]:1:2
at Interface. (repl:96:19)
at Interface.emit (events:31:17)
at Interface._ttyWrite (readline:309:12)
at Interface.write (readline:147:30)
at Stream. (repl:79:9)
at Stream.emit (events:31:17)
at IOWatcher.callback (net:489:16)
*/
EDIT:
hyperNum.prototype.valueOf = function(){return this.q;}
made it.
However still is it better to use a different object or just to extend the Number object?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…