So lets say I want to make a simple Price class in JS. It’s basically a number so I thought I would just inherit from a Number. Here is some code:
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.
I probably do something wrong, but I can’t find out what.
You have a typo in this line I think:
You are assigning a new Number to be the prototype of Price so you need to use an = sign not a minus sign.
It should read:
Having said that, it still doesn’t work. I can’t understand why you are attempting to inherit from Number.
This works: