我可以创建一个被隐式转换为数字的javascript对象吗? [英] Can I create a javascript object that is casted implicitly as number?
本文介绍了我可以创建一个被隐式转换为数字的javascript对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个具有多个公共变量和方法的类,但应用算术运算符时,它的行为类似于数字。例如:
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`
我知道我可以重载Number对象,但是我认为会有一定的开销, 。
当我尝试继承Number时,出现错误:
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)
*/
编辑:
hyperNum.prototype.valueOf = function(){return this.q;}
创建了。
但是仍然最好使用不同的对象或者只是扩展Number对象?
However still is it better to use a different object or just to extend the Number object?
推荐答案
实现 valueOf
,无需扩展 Number
即可:
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"
这篇关于我可以创建一个被隐式转换为数字的javascript对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文