【发布时间】:2011-06-19 09:52:51
【问题描述】:
我想创建一个具有多个公共变量和方法的类,但在应用算术运算符时表现为数字。示例:
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 对象更好?
【问题讨论】:
-
至少在 JavaScript 中没有运算符重载。
-
@pimvdd:不,但是
valueOf和toString函数为对象提供了有用的功能...
标签: javascript oop casting