'Add attribute to instance of "Number"
I want to see if a number is a multiple of π. So ideally it would behave exactly like an ordinary number, but with extra functionality:
>>> pi
3.14...
>>> pi.isMultipleOfPi
true
>>> b = pi * 5
>>> b.isMultipleOfPi
true
With wishful thinking
>>> c = pi + 1
>>> c.isMultipleOfPi
false
>>> d = pi + 2 * pi
>>> d.isMultipleOfPi
true
Is there a way to achieve something like that in Javascript? I think this would be pretty straight forward in Python, but there seems to be no way to create overloads for addition/multiplication etc. in JS. If there were, I could simply extent the Number class.
Setting something on Number.prototype = function also doesn't seem to work as it sets it for the entire class and not on an instance.
Solution 1:[1]
You cannot add properties to specific number values; they are not objects and thus they can't have any properties. You can add properties to the Number prototype, as follows:
Object.defineProperty(Number.prototype, "isMultipleOfPi", {
get: function() {
return this.valueOf() % Math.PI === 0;
}
});
const pix2 = Math.PI * 2;
console.log(pix2.isMultipleOfPi);
console.log((7).isMultipleOfPi);
That adds a Number prototype property defined with a "get" function so that the code you posted will work as you expect. The method will be available for all numbers in your program, which doesn't seem like a bad thing if you want that feature at all.
Note also that extending built-in prototype objects is frowned upon by many people. In my example, I extended the prototype in a way that ameliorates some of the problems with extended prototypes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
