Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
698 views
in Technique[技术] by (71.8m points)

oop - Can I create a javascript object that is casted implicitly as number?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can just implement valueOf, no need to extend Number to do it:

function Foo(val) {
  this.val = val;
}
Foo.prototype.valueOf = function() {
  return this.val;
};
Foo.prototype.toString = function() {
  return "Foo: " + this.val;
};

display("f = " + f);                      // "f = 42"
display("f + 1 = " + (f + 1));            // "f + 1 = 43"
display("f * 2 = " + (f * 2));            // "f * 2 = 84"
display("f as a string = " + String(f));  // "f as a string = Foo: 42"

Live example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...