假设我想在 JS 中创建一个简单的 Price 类。它基本上是一个数字,所以我想我会继承一个数字。这是一些代码:
Number.prototype.toMoney = function (precision, decimals, thousands) {
// Formats number...
}
function Price(val) {
Number.call(val); // Based on MozillaDN
}
Price.sufix = ' EUR'; // To print with every Price
// Price.prototype = Number.prototype;
Price.prototype = new Number(); // any difference?
Price.prototype.toString = function() {
return this.toMoney() + Price.sufix; // Of course it does not work.
}
var price = new Price(100.50);
alert(price.toString()); // Gives: undefined EUR
alert(price); // This fail. I thought it should work as it works with Numbers.
我可能做错了什么,但我不知道是什么。
最佳答案
当我寻找几乎相同问题的答案时,我找到了此页面。因为这帮助我做出了最终结论,所以我想与大家分享。确实可以从 Number 继承自己的对象。
function Price(val) {
Number.call(this, val);
}
这是您通常调用父对象的构造函数的方式,但在这种情况下它不起作用,因为构造函数返回 val
本身。当您尝试读取 val
时,会收到“Number.prototype.valueOf is not generic”错误。
alert(price.toString()); // Gives: undefined EUR
alert(price); // This fail. I thought it should work as it works with Numbers.
alert(price.valueOf()); // This fails too! ()
相反,您应该在 Price 类中创建一个名为 val
的属性。
function Price(val) {
this.val = val;
}
Price.sufix = ' EUR'; // To print with every Price
// Price.prototype = Number.prototype;
Price.prototype = new Number(); // any difference?
JavaScript 中有一种方法可以实现继承对象,即 Object.create()
方法。并且因为构造函数对象现在指向父级的构造函数,...
Price.prototype = Object.create(Number.prototype);
Price.prototype.constructor = Price;
最后,您可以重写valueOf()
方法来读取值:
Price.prototype.valueOf = function(){
return this.val;
}
var price = new Price(100.50);
alert(price); //should work now
但是,有一个副作用:如果您需要 Number 对象的方法,则必须像这样调用它们:
alert(price.valueOf().toFixed(2));
关于JavaScript 数字继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10961639/