我想创建一个具有多个公共(public)变量和方法的类,但在应用算术运算符时表现为数字。示例:
a = new hyperNum(4)
a.func(4)
a.assign(2.0)
alert(a + 1.0) `//3.0`
我知道我可以重载 Number 对象,但我认为所有数字都会有一定的开销。 当我尝试从 Number 继承时,出现错误:
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 对象更好?
最佳答案
您只需实现 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 - 我可以创建一个隐式转换为数字的 JavaScript 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6401721/