继承javascript编号以更改toString
我正在尝试从Number继承,以重写toString方法,以便在调用toString时输出固定小数点:继承javascript编号以更改toString,javascript,node.js,inheritance,prototype,Javascript,Node.js,Inheritance,Prototype,我正在尝试从Number继承,以重写toString方法,以便在调用toString时输出固定小数点: function FixedNumber(value) { Number.call(this, value); } util.inherits(FixedNumber, Number); FixedNumber.prototype.toString = function() { return this.toFixed(3); } var n = new FixedNumb
function FixedNumber(value) {
Number.call(this, value);
}
util.inherits(FixedNumber, Number);
FixedNumber.prototype.toString = function() {
return this.toFixed(3);
}
var n = new FixedNumber(5);
var s = n.toString();
不幸的是,这不起作用。我得到以下例外情况:
TypeError: Number.prototype.valueOf is not generic
at FixedNumber.valueOf (native)
at FixedNumber.toFixed (native)
at FixedNumber.toString (repl:2:13)
at repl:1:3
at REPLServer.self.eval (repl.js:110:21)
at repl.js:249:20
at REPLServer.self.eval (repl.js:122:7)
at Interface.<anonymous> (repl.js:239:12)
at Interface.EventEmitter.emit (events.js:95:17)
at Interface._onLine (readline.js:202:10)
TypeError:Number.prototype.valueOf不是泛型
at FixedNumber.valueOf(本机)
at FixedNumber.toFixed(本机)
在FixedNumber.toString(回复:2:13)
回复:1:3
在REPLServer.self.eval(repl.js:110:21)
回复js:249:20
在REPLServer.self.eval(repl.js:122:7)
在接口处。(回复js:239:12)
位于Interface.EventEmitter.emit(events.js:95:17)
在接口处在线(readline.js:202:10)
我做错了什么,怎么做我想做的事?当
Number
被作为函数调用时(就像您对其使用call
时所发生的情况),它的行为与“普通”构造函数不同——相反,它只是将参数转换为一个数字
15.7.1.1编号([值])
返回由ToNumber(value)计算的数字值(不是数字对象),如果提供了值,则返回+0
除此之外,它什么也不做。实际上,您返回的是一个普通对象,其原型基于编号。prototype
——未设置存储实际编号的内部属性
由于返回的对象不是数字对象,它会失败,因为Number.prototype.toString
不是泛型,这意味着它只能用于实际的数字对象或原语。即使它没有抛出错误,也可能返回“NaN”
,因为如果没有设置,这是默认值
现在确实没有“干净”的方法来实现这一点,尽管通过对本机构造函数进行子类化,ES6也可以做到这一点
虽然这是一种黑客行为,而且相当混乱,但您可以执行以下操作:
function FixedNumber(num) {
this.toString = function () {
return num.toFixed(3);
};
// implement the rest of Number.prototype as instance methods
}
// make instanceof return true
FixedNumber.prototype = Object.create(Number.prototype);
将这些方法放在原型上并不切实可行,因为无法访问存储的实际数字。当将
数字
作为函数调用时(就像在其上使用调用时所发生的情况),它的行为不像“普通”构造函数——相反,它只是将参数转换为数字
15.7.1.1编号([值])
返回由ToNumber(value)计算的数字值(不是数字对象),如果提供了值,则返回+0
除此之外,它什么也不做。实际上,您返回的是一个普通对象,其原型基于编号。prototype
——未设置存储实际编号的内部属性
由于返回的对象不是数字对象,它会失败,因为Number.prototype.toString
不是泛型,这意味着它只能用于实际的数字对象或原语。即使它没有抛出错误,也可能返回“NaN”
,因为如果没有设置,这是默认值
现在确实没有“干净”的方法来实现这一点,尽管通过对本机构造函数进行子类化,ES6也可以做到这一点
虽然这是一种黑客行为,而且相当混乱,但您可以执行以下操作:
function FixedNumber(num) {
this.toString = function () {
return num.toFixed(3);
};
// implement the rest of Number.prototype as instance methods
}
// make instanceof return true
FixedNumber.prototype = Object.create(Number.prototype);
将这些方法放在原型上并不切实可行,因为无法访问存储的实际数字